Linux C: 使用 fwrite 将字符写入不同的行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10256116/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 05:55:51  来源:igfitidea点击:

C: use fwrite to write char to different line

clinuxfile-iofwrite

提问by Jake

I have to write to a file as follows:

我必须按如下方式写入文件:

 A
 B
 C
 D
 ...

Each character of the alphabet needs to be written to different line in the file. I have the following program which writes characters one after another:

字母表的每个字符都需要写入文件中的不同行。我有以下程序一个接一个地写字符:

 FILE* fp;
 fp = fopen("file1","a+");
 int i;
 char ch= 'A';
 for(i=0; i<26; i++){
     fwrite(&ch, sizeof(char), 1, fp);
     ch++;
 }
 fclose(fp);

How should I change the above program to write each character to a new line. (I tried writing "\n" after each character, but when I view the file using VI editor or ghex tool, I see extra characters; I am looking for a way so that vi editor will show file exactly as shown above).

我应该如何更改上述程序以将每个字符写入新行。(我尝试在每个字符后写入“\n”,但是当我使用 VI 编辑器或 ghex 工具查看文件时,我看到了额外的字符;我正在寻找一种方法,以便 vi 编辑器能够完全如上所示显示文件)。

I tried using the following after first fwrite:

我在第一次 fwrite 后尝试使用以下内容:

 fwrite("\n", sizeof("\n"), 1, fp);

Thanks.

谢谢。

采纳答案by dasblinkenlight

fwrite("\n", sizeof("\n"), 1, fp);

should be

应该

fwrite("\n", sizeof(char), 1, fp);

Otherwise, you are writing an extra \0that is part of zero-termination of your "\n"string constant (sizeof("\n")is two, not one).

否则,您正在编写一个额外\0"\n"字符串常量零终止的一部分(sizeof("\n")是两个,而不是一个)。

回答by Jim Mischel

What "extra characters" do you see? You do realize that the "a+"parameter to fopenopens the file for appending, so that you're writing to the end of the file. Did you perhaps mean "w+", which will overwrite the file?

你看到了什么“额外字符”?您确实意识到打开文件以进行追加的"a+"参数fopen,因此您正在写入文件的末尾。您可能是说"w+",这会覆盖文件吗?

You could use:

你可以使用:

fputc((int)ch, fp);
fputc((int)'\n', fp);

Or even fprintf(fp, "%c\n", ch);

甚至 fprintf(fp, "%c\n", ch);