Anonymous
Anonymous asked in 電腦與網際網路程式設計 · 1 decade ago

c++ 讀取txt的問題

我要讀取一個txt檔,可以確定的是每次txt檔的資料都是一串的

txt檔裡面的內容例如:1234567890abcdefg

但是每次的長度不一定,txt檔裡面的內容可能是1個也可能是100個

需求:

要讀取txt檔裡面的資料,並且判斷出資料的長度

假設資料為:1234567890abc

那長度就是:12 (從0開始算)

==========================================

以下是本來想到的辦法

file=fopen("host_code.txt","rb");

if(file==0) //file not exist

return 0;

memset(buffer,0x00,sizeof(buffer));

fread(buffer,1,256,file); // <------ 使用fread,但是這個函式要設定讀取長度,偏偏長度不一定

fclose(file);

return 0;

所以有更好的函式可以符合我的需求嗎?

因為以上是C的函式,那如果用C++的函式,可以使用那一個?

1 Answer

Rating
  • 1 decade ago
    Favorite Answer

    上次剛好有問到

    // Copy a file

    #include <fstream>

    #include <iostream>

    using namespace std;

    int main () {

    char * buffer;

    long size;

    ifstream infile ("test.txt",ifstream::binary);

    ofstream outfile ("1new.txt",ofstream::binary);

    // get size of file 取得檔案長度

    infile.seekg(0,ifstream::end);

    size=infile.tellg();

    infile.seekg(0);

    // allocate memory for file content

    buffer = new char [size];

    // read content of infile

    infile.read (buffer,size);

    cout << buffer;

    // write to outfile

    outfile.write (buffer,size);

    // release dynamically-allocated memory

    delete[] buffer;

    outfile.close();

    infile.close();

    system("pause");

    return 0;

    }

    • Commenter avatarLogin to reply the answers
Still have questions? Get your answers by asking now.