将文本文件读入字符数组。C++ ifstream

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4373047/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 15:15:31  来源:igfitidea点击:

Read text file into char Array. C++ ifstream

c++arrayscharifstream

提问by nubme

Im trying to read the whole file.txt into a char array. But having some issues, suggestions please =]

我试图将整个 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]
 }

采纳答案by tmiddlet

Every time you read a new line you overwrite the old one. Keep an index variable i and use infile.read(getdata+i,1)then increment i.

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

回答by Vertexwahn

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);

回答by 0x499602D2

Use std::string:

使用std::string

std::string contents;

contents.assign(std::istreambuf_iterator<char>(infile),
                std::istreambuf_iterator<char>());

回答by Tony Delroy

You don't need to read line by line if you're planning to suck the entire file into a buffer.

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

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...

}

回答by Victor Resnov

You could use Tony Delroy's answer and incorporate a little function to determine the size of the file, and then create the chararray of that size, like this:

您可以使用 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;
}

Then you can do this:

然后你可以这样做:

//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...
}