读取和写入文件C++

Reading and writing to files C++

本文关键字:文件 C++ 读取      更新时间:2023-10-16

我有关于文件输出/输入的问题。 这是我的程序:

#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? 如何写入文件(任何类型的(来克服此问题?
我正在寻找一种将值(任何范围,可以是charint或其他(自由写入文件然后读取它的方法。

对我有用*(,但是有一些评论:

  1. 不应使用#include <bits/stdc++.h>,这是一个供编译器使用的内部标头,不应包含在客户端应用程序中。
  2. 由于某些字符被翻译(例如 EOL(或在文本(默认(模式下专门解释,您应该以二进制模式打开文件。
  3. 读取为(有符号(字符并转换为 int 将导致负值超过 127。
  4. 由于fgetc已经返回 int,因此您实际上根本不需要将转换为有符号字符并返回。

请参阅此处包含更正的代码。

*(显然,正如其他评论中提到的,它可能不适用于文本模式下的Windows(请参阅第2点(。

我正在寻找一种自由地将值(任何范围,可以是字符、int 或其他(写入文件然后读取它的方法。

在这种情况下,您必须:

用分隔符
  • 分隔各个值,例如空格或换行符。
  • 读回整数而不是单个单独的字符/字节。

最简单的方法是使用C++std::fstream。 例如:

int main() {
{
std::ofstream out("tmp.txt");
for(int i=0; i<256; i++)
out << i << 'n';
// out destructor flushes and closes the stream.
}
{
std::ifstream in("tmp.txt");
for(int c; in >> c;)
std::cout << c << 'n';
}
}