相關文章
C++檔案讀寫操作(一)将字母表寫入TXT文本檔案
C++檔案讀寫操作(二)逐字元讀取文本和逐行讀取文本
C++檔案讀寫操作(三)如何統計文本的行數及如何讀取檔案某一行内容
C++檔案讀寫操作(四)讀取檔案資料到臨時數組
//讀取檔案資料到臨時數組
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int CountLines(char *filename)
{
ifstream ReadFile;
int n=0;
string tmp;
ReadFile.open(filename,ios::in);//ios::in 表示以隻讀的方式讀取檔案
if(ReadFile.fail())//檔案打開失敗:傳回0
{
return 0;
}
else//檔案存在
{
while(getline(ReadFile,tmp,'\n'))
{
n++;
}
ReadFile.close();
return n;
}
}
int main()
{
ifstream file;
int LINES;
char filename[512]="inFile.txt";
file.open(filename,ios::in);
if(file.fail())
{
cout<<"檔案不存在."<<endl;
file.close();
}
else//檔案存在
{
LINES=CountLines(filename);
int *tempInt=new int[LINES];
char *tempChar=new char[LINES];
int i=0;
while(!file.eof()) //讀取資料到數組
{
file>>tempInt[i];
file>>tempChar[i];
i++;
}
file.close(); //關閉檔案
for(i=0;i<LINES;i++)//輸出數組内容
cout<<tempInt[i]<<"\t"<<tempChar[i]<<endl;
delete []tempInt;
delete []tempChar;
}
}