我想用C写多行,当我输入空行时,退出写,到目前为止我只写一个字的文本.
printf("Enter new file name ,or the file which you want to edit: ");
scanf("%s",filename);
snprintf(buffer1, sizeof(buffer1), "C:\\Proiect\\%s.txt", filename);
FILE *OutFile = fopen(buffer1,"w");
scanf("%s",write_in_file);
fprintf(OutFile,"%s",write_in_file);
fclose(OutFile);
printf("File %s created!",filename);编辑,我不知道为什么,在我运行这段代码之后,在我写第一个单词之后,我的代码就崩溃了.
printf("Enter new file name ,or the file which you want to edit: ");
scanf("%s",filename);
snprintf(buffer1, sizeof(buffer1), "C:\\Proiect\\%s.txt", filename);
char line[256];
FILE *OutFile = fopen(buffer1,"w");
do {
fgets(line,256,stdin);
fprintf(OutFile,line);
//Your code to store the line to the file.
}while(line[0] != '\n');
fclose(OutFile);发布于 2015-10-06 08:31:35
使用fgets()。正如文件上说的,
fgets()从流中读取最多小于一个小于大小的字符,并将它们存储到由s指向的缓冲区中。读取在EOF或换行符之后停止。如果读取换行符,则将其存储到缓冲区中。在缓冲区中的最后一个字符之后存储终止空字节(aq\0aq)。
唯一需要记住的是,线的大小有一个上限。因此,例如,如果程序将获得的最大行大小为255(\0为+1),则代码如下所示
char line[256];
do {
fgets(line,256,stdin);
//Your code to store the line to the file.
}while(line[0] != '\n')https://stackoverflow.com/questions/32965012
复制相似问题