fwrite、fprintf、fputc等写文件函数都可以完成,而专用的字符串文件写入函数fputs更方便一些。举例如下(文件建立在当前目录下,名为123.txt):
//#include "stdafx.h"//If the vc++6.0, with this line.
#include "stdio.h"
#include "string.h"
#include "stdlib.h"
int main(void){
char s[70];
FILE *fp;
if((fp=fopen("123.txt","w"))==NULL){
printf("Open the file failure...\n");
exit(0);
}
while(1){
printf("Input a string...\ns=");
if(gets(s),strlen(s)<70)
break;
printf("Too long, redo: ");
}
fputs(s,fp);
fclose(fp);
printf("\n");
return 0;
}
使用fopen() fwrite() 等函数,详细可以参考c/c++标准库。下面是一个示例代码,向1.txt中写入20字节的字串。
#include
int main()
{
char str[20] = "testtesttesttesttes";
FILE *fp = fopen("1.txt", "w+");
if (fp==0) {
printf("can't open file\n");
return 0;
}
fwrite(str, sizeof(char)*20, 1, fp);
fclose(fp);
return 0;
}
#include
void main()
{
char str[200];
FILE *fp;
printf("请输入一个字符串:\n");
gets(str);
if((fp=fopen("test.txt","wt"))==NULL)
{
printf("cannot open file\n");
return;
}
fprintf(fp,"%s",str);
fclose(fp);
}