C++写数据追加方式到文件

#include 
#include
using namespace std;
ofstream outfile;
void writeLog()

 outfile.open("C:\\myfile.txt", ios::app);
  if(!outfile) //检查文件是否正常打开//不是用于检查文件是否存在
 {
  cout<<"abc.txt can't open"<<endl;
  abort(); //打开失败,结束程序
 }
 else
 {
  outfile << "world" << endl;
  outfile.close();
 }
}
void writeLog2()
{
 outfile.open("C:\\myfile.txt", ios::app);
 if(!outfile) //检查文件是否正常打开
 {
  cout<< "abc.txt can't open"<< endl;
  abort(); //打开失败,结束程序
 }
 else
 {
  outfile << "Write log2" << endl;
  outfile.close();
 }
}
int main(int argc, char* argv[])
{
 writeLog();
 writeLog2();
 printf("Hello World!\n");
 return 0;
}
要在C/C++中将数据入文本文件,可以使用标准库中的文件流类fstream。 以下是一个简单的示例代码: ```cpp #include <fstream> int main() { std::ofstream outfile("data.txt"); // 创建文件流对象并打开文件 if (outfile.is_open()) { // 检查文件是否成功打开 outfile << "Hello, world!" << std::endl; // 数据文件 outfile.close(); // 关闭文件 } else { // 文件打开失败 } return 0; } ``` 在上面的示例中,我们首先创建了一个std::ofstream对象outfile,并指定要入的文件名。然后,我们使用is_open()方法检查文件是否成功打开。如果文件成功打开,我们使用“<<”操作符将数据写入文件,并使用close()方法关闭文件。 需要注意的是,如果文件已经存在,上述代码将会覆盖原有的内容。如果想要将数据追加文件末尾,可以使用std::ios::app模式打开文件。例如: ```cpp std::ofstream outfile("data.txt", std::ios::app); // 使用追加模式打开文件 ``` 另外,可以使用格式化输出函数,例如printf()或fprintf(),将数据格式化后写入文件。例如: ```cpp #include <cstdio> int main() { FILE* outfile = fopen("data.txt", "w"); // 打开文件 if (outfile != nullptr) { // 检查文件是否成功打开 double pi = 3.1415926535; int n = 42; fprintf(outfile, "pi = %.10f\n", pi); // 将格式化的数据写入文件 fprintf(outfile, "n = %d\n", n); fclose(outfile); // 关闭文件 } else { // 文件打开失败 } return 0; } ``` 在上面的示例中,我们使用fopen()函数打开文件,并得到一个FILE*类型的指针。然后,我们使用fprintf()函数将格式化的数据写入文件,最后使用fclose()函数关闭文件。 需要注意的是,使用fprintf()函数需要手动指定文件指针,而不是像ofstream那样使用“<<”操作符。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值