读取和写入文件C++
Reading and writing to files 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
或其他(自由写入文件然后读取它的方法。
对我有用*(,但是有一些评论:
- 不应使用
#include <bits/stdc++.h>
,这是一个供编译器使用的内部标头,不应包含在客户端应用程序中。 - 由于某些字符被翻译(例如 EOL(或在文本(默认(模式下专门解释,您应该以二进制模式打开文件。
- 读取为(有符号(字符并转换为 int 将导致负值超过 127。
- 由于
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';
}
}
相关文章:
- .cpp和.h文件中的模板专用化声明
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 文本文件中的单词链表
- CMake-按正确顺序将项目与C运行时对象文件链接
- 使用新行和不使用新行读取文件
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 挂起和取消挂起一个文件DLL
- 如何确定我已使用非编码文件到达 EOF?
- 命名空间中具有.h和.cpp文件的类
- 如何使用ndk-build.cmd构建Android.so文件
- 从包含m行的文件中提取n行,必要时(惰性地)重复该文件
- 读取文件并输入到矢量中
- 在C++中查找文件
- c++库的公共头文件中应该包含什么
- 用c++从输入文件中读取另一行
- Cppcheck生成xml转储文件
- 读取文件的最后一行并输入到链接列表时出错
- 无法编译 rtmidi 测试 cmidiin.cpp 文件, 非法指令
- 如何将内容数组写入文本文件?
- C++ Windows 驱动程序MSB3030无法复制该文件,因为它找不到