读写文件C ++

时间:2017-07-25 11:53:24

标签: c++ file

我对文件的输出/输入有疑问。 这是我的计划:

#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或者其他)写入文件,然后阅读它。

2 个答案:

答案 0 :(得分:2)

Works for me *),但有几点评论:

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

    *)显然在文本模式中的其他评论it might not work on Windows中提到过(参见第2点)。

答案 1 :(得分:2)

  

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

在这种情况下,您必须:

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

最简单的方法是使用C ++ std::fstream。 E.g:

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';
    }
}
相关问题