操作文件必須包含的頭文件:#include <fstream>
寫入:
int main ()
{
string fileName = "e:\\vs2012\\file\\a.csv";
ofstream file(fileName);
if(!file){cout << "open file error" <<endl; return 0;}
for (int i = 0; i < 1000000; i++)
{
file<<i<<",username"<<i<<",pw"<<i<<"\n";
}
file.close();
}
讀取:
string str;
ifstream file(fileName , ios::in);
file>>str;
cout << str <<endl;
while(!file.eof()){ //多行讀取
getline(file,str);
cout<<str<<endl;
}
文件打開方式選項:
ios::
in
= 0x01,
//供讀,文件不存在則創建(ifstream默認的打開方式)
ios::
out
= 0x02,
//供寫,文件不存在則創建,若文件已存在則清空原內容(ofstream默認的打開方式)
ios::ate = 0x04,
//文件打開時,指針在文件最后。可改變指針的位置,常和in、out聯合使用
ios::app = 0x08,
//供寫,文件不存在則創建,若文件已存在則在原文件內容后寫入新的內容,指針位置總在最后
ios::trunc = 0x10,
//在讀寫前先將文件長度截斷為0(默認)
ios::nocreate = 0x20,
//文件不存在時產生錯誤,常和in或app聯合使用
ios::noreplace = 0x40,
//文件存在時產生錯誤,常和out聯合使用
ios::binary = 0x80
//二進制格式文件
CSV格式的文件,可以用excel打開,格式和txt一樣,每列用英文逗號隔開,每行用\n
方法1:(c語言)
int main()
{
FILE *f;
f = fopen("e:\\a.csv" , "wb");
fprintf(f,"aaa,23,sdf\n");
fprintf(f,"bbb/,,345\,,2sdf\n");
fclose(f);
return 0;
}
load data infile 'E:\\vs2012\\file\\a.csv' into table test fields terminated by ',' optionally enclosed by '"' lines terminated by '\r\n';
//判斷文件是否存在的方法, WIN32_FIND_DATA FindFileData; HANDLE hFind; hFind = FindFirstFile(file_path.c_str(), &FindFileData); if(hFind == INVALID_HANDLE_VALUE){ cout<<"failed"<<endl; printf("%d", GetLastError()); }