1 c
一个新的空文件:
touch /file.txt
Run Code Online (Sandbox Code Playgroud)
读.打印.
fp = fopen("/file.txt", "r");
char text[1000];
int i=0;
while(!feof(fp)){
text[i++] = getc(fp);
}
text[i]='\0';
printf("%s\n", text);
Run Code Online (Sandbox Code Playgroud)
结果:
ÿ
Run Code Online (Sandbox Code Playgroud)
EXTRA INFO:如果file.txt有很多行..它会在它的最底部附加那个奇怪的字符.所以也许并不是每个"while循环"都会发生的事情.
如果您使用的是ISO 8859-15或8859-1代码集,则ÿ(带有DIAERESIS的LATIN SMALL LETTER Y,Unicode中的U + 00FF)代码为255 10或0xFF.将EOF存储在数组中时,它将转换为ÿ.
不要将EOF存储在char
.并记住,getchar()
返回一个int
,而不是一个char
.它必须能够返回可以存储在a中的每个值unsigned char
,加上EOF是负的(通常但不一定-1
).
并且,如评论中所述,while (!feof(file))
总是错误的.这只是另一个原因.
此代码或多或少是固定的.如果无法打开文件,它应该报告错误.请注意,它还确保您不会溢出缓冲区.
FILE *fp = fopen("/file.txt", "r");
if (fp != 0)
{
char text[1000];
int i=0;
int c;
while ((c = getc(fp)) != EOF && i < sizeof(text)-1)
text[i++] = c;
text[i]='\0';
printf("%s\n", text);
fclose(fp);
}
Run Code Online (Sandbox Code Playgroud)
另请参见while ((c = getc(file)) != EOF)
循环不会停止执行.
该ÿ
是你的代码页,这是不变的字节255 EOF
强制转换为char
.feof
您必须将返回值存储getc
为a int
,然后将其与之进行比较,而不是使用,EOF
这是一个易于阅读的示例(请注意,您还必须进行边界检查):
while (1) {
int c = getc(fp);
if (c == EOF) {
break;
}
text[i++] = c;
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
552 次 |
最近记录: |