簡體   English   中英

將文本文件讀入char數組。 C ++ ifstream

[英]Read text file into char Array. C++ ifstream

我試圖將整個file.txt讀入一個char數組。 但有一些問題,建議請=]

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

使用std::string

std::string contents;

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

如果您計划將整個文件吸入緩沖區,則無需逐行讀取。

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

}

每次讀取新行時都會覆蓋舊行。 保留索引變量i並使用infile.read(getdata+i,1)然后遞增i。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM