6

我试图将整个 file.txt 读入一个字符数组。但是有一些问题,请提出建议=]

ifstream infile;
infile.open("file.txt");

char getdata[10000]
while (!infile.eof()){
  infile.getline(getdata,sizeof(infile));
  // if i cout here it looks fine
  //cout << getdata << endl;
}

 //but this outputs the last half of the file + trash
 for (int i=0; i<10000; i++){
   cout << getdata[i]
 }
4

5 回答 5

6
std::ifstream infile;
infile.open("Textfile.txt", std::ios::binary);
infile.seekg(0, std::ios::end);
size_t file_size_in_byte = infile.tellg();
std::vector<char> data; // used to store text data
data.resize(file_size_in_byte);
infile.seekg(0, std::ios::beg);
infile.read(&data[0], file_size_in_byte);
于 2013-02-05T22:47:11.473 回答
3

使用std::string

std::string contents;

contents.assign(std::istreambuf_iterator<char>(infile),
                std::istreambuf_iterator<char>());
于 2013-11-07T02:03:40.520 回答
2

如果您打算将整个文件吸入缓冲区,则无需逐行阅读。

char getdata[10000];
infile.read(getdata, sizeof getdata);
if (infile.eof())
{
    // got the whole file...
    size_t bytes_really_read = infile.gcount();

}
else if (infile.fail())
{
    // some other error...
}
else
{
    // getdata must be full, but the file is larger...

}
于 2010-12-07T03:52:33.453 回答
1

每次阅读新行时,都会覆盖旧行。保留一个索引变量 i 并使用infile.read(getdata+i,1)然后递增 i。

于 2010-12-07T03:19:37.070 回答
0

您可以使用 Tony Delroy 的答案并结合一个小函数来确定文件的大小,然后创建该char大小的数组,如下所示:

//Code from Andro in the following question: https://stackoverflow.com/questions/5840148/how-can-i-get-a-files-size-in-c

int getFileSize(std::string filename) { // path to file
    FILE *p_file = NULL;
    p_file = fopen(filename.c_str(),"rb");
    fseek(p_file,0,SEEK_END);
    int size = ftell(p_file);
    fclose(p_file);
    return size;
}

然后你可以这样做:

//Edited Code From Tony Delroy's Answer
char getdata[getFileSize("file.txt")];
infile.read(getdata, sizeof getdata);

if (infile.eof()) {
    // got the whole file...
    size_t bytes_really_read = infile.gcount();
}
else if (infile.fail()) {
    // some other error...
}
于 2019-03-14T01:05:27.027 回答