xcode fread() 将奇怪的东西放入 char 数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9433174/
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
fread() puts weird things into char array
提问by CoffeeRain
I have a file that I want to be read from and printed out to the screen. I'm using XCode as my IDE. Here is my code...
我有一个文件,我想从中读取并打印到屏幕上。我使用 XCode 作为我的 IDE。这是我的代码...
fp=fopen(x, "r");
char content[102];
fread(content, 1, 100, fp);
printf("%s\n", content);
The content of the file is "Bacon!" What it prints out is \254\226\325k\254\226\234
.
文件的内容是“培根!” 它打印出来的是\254\226\325k\254\226\234
.
I have Googled all over for this answer, but the documentation for file I/O in C seems to be sparse, and what little there is is not very clear. (To me at least...)
我在谷歌上到处搜索这个答案,但是 C 中文件 I/O 的文档似乎很少,而且还不是很清楚。(至少对我来说...)
EDIT: I switched to just reading, not appending and reading, and switched the two middle arguments in fread()
. Now it prints out Bacon!\320H\320
What do these things mean? Things as in backslash number number number or letter. I also switched the way to print it out as suggested.
编辑:我切换到只阅读,而不是追加和阅读,并在fread()
. 现在它打印出Bacon!\320H\320
这些东西是什么意思?反斜杠数字数字或字母中的东西。我也按照建议切换了打印方式。
回答by dasblinkenlight
You are opening the file for appending and reading. You should be opening it for reading, or moving your read pointer to the place from which you are going to read (the beginning, I assume).
您正在打开文件进行追加和阅读。您应该打开它进行阅读,或者将您的阅读指针移动到您要阅读的位置(我假设是开头)。
FILE *fp = fopen(x, "r");
or
或者
FILE *fp = fopen(x, "a+");
rewind(fp);
Also, fread(...)
does not zero-terminate your string, so you should terminate it before printing:
此外,fread(...)
不会以零终止您的字符串,因此您应该在打印前终止它:
size_t len = fread(content, 1, 100, fp);
content[len] = 'printf("%s\n", content);
';
printf("%s\n", content);
回答by arrowd
I suppose, you meant this:
我想,你的意思是:
fp = fopen(x, "a+");
if(fp)
{
char content[102];
memset(content, 0 , 102);
// arguments are swapped.
// See : http://www.cplusplus.com/reference/clibrary/cstdio/fread/
// You want to read 1 byte, 100 times
fread(content, 1, 100, fp);
printf("%s\n", content);
}
回答by arrowd
Maybe:
也许:
##代码##回答by Some programmer dude
A possible reason is that you do not terminate the data you read, so printf
prints the buffer until it finds a string terminator.
一个可能的原因是您没有终止读取的数据,因此printf
打印缓冲区直到找到字符串终止符。