[英]Using Ubuntu gedit to write to a file
我正在嘗試編寫一個簡單的程序來寫入已經存在的文件。 我收到此錯誤:
hello2.txt: file not recognized: File truncated
collect2: ld returned 1 exit status
我究竟做錯了什么? (我嘗試了兩種方式的斜線,但我仍然得到同樣的錯誤。)
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
ofstream outStream;
outStream.open(hello3.txt);
outStream<<"testing";
outStream.close;
return 0;
}
其中有兩個錯誤:
hello3.txt 是一個字符串,因此應該用引號引起來。
std::ofstream::close() 是 function,因此需要括號。
更正后的代碼如下所示:
#include <iostream>
#include <fstream>
int main()
{
using namespace std; // doing this globally is considered bad practice.
// in a function (=> locally) it is fine though.
ofstream outStream;
outStream.open("hello3.txt");
// alternative: ofstream outStream("hello3.txt");
outStream << "testing";
outStream.close(); // not really necessary, as the file will get
// closed when outStream goes out of scope and is therefore destructed.
return 0;
}
請注意:此代碼會覆蓋該文件中以前的任何內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.