我有关于文件输出/输入的问题。 这里是我的程序:正在读取和写入文件C++
#include <bits/stdc++.h>
using namespace std;
int main()
{
FILE * out;
out=fopen("tmp.txt", "w");
for(int i=0; i<256; i++)
{
fprintf(out, "%c", char(i));
}
fclose(out);
FILE * in;
in=fopen("tmp.txt", "r");
while(!feof(in))
{
char a=fgetc(in);
cout<<int(a)<<endl;
}
fclose(in);
}
这里是输出:
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
-1
为什么这么快就停止? 这是否意味着char(26)
是EOF
? 我怎么能写入文件(任何类型)来克服这个问题?
我正在寻找的是一种自由将值(任何范围,可以是char
,int
或其他)写入文件然后阅读它的方法。
除了无偿使用'std :: cout'和(滥用)'std :: endl'这是一个C问题。改变您的控制台输出使用'printf'并放入一个C标签;你会得到更好的答案。在C++中,文件I/O通过'std :: ifstream'和'std :: ofstream'完成。 –
对于C++中的文件I/O,您可能需要使用[std :: ifstream和std :: ofstream](http://www.cplusplus.com/doc/tutorial/files/) – HatsuPointerKun
您不应该使用'char '返回'fgetc'。它的返回类型是“int”。你返回'-1'意味着你读的字符很可能是字符'0xFF'。 'EOF'通常被定义为整数'-1'。你不能以当前的形式区分它们。 – Lanting