在网上看了很多,发现写入文件内容的比较多
一、利用C++来写入文件
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
freopen("123.txt", "r", stdin);//打开文件
freopen("123.txt", "w", stdout);//如果没有文件,则会自动进行添加
//开始进行写入文件
printf("hello world1");
//写入完毕
fclose(stdout);
while (1);
return 0;
}
二、读写操作
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
//创建一个文本并向里面输入内容
ofstream OutputFile("test.txt");//创建一个txt文本
OutputFile << "hello meimei";//输入文本内容
OutputFile.close();//关闭文件
//读取文本的内容
ifstream readstreamFile("test.txt");//打开test.txt的文本
char a[1024];
readstreamFile >> a;//这种方式的输出会导致只要遇到空格就会直接退出
// readstreamFile.getline(a, 100, 0);//这种方式的输出是可以直接将里面的内容进行输出
cout << a << endl;
readstreamFile.close();
while (1);
return 0;
}
三、发现一篇大神的博客参考博客:https://blog.csdn.net/kingstar158/article/details/6859379
以下内容是参考大神博客进行改编
可以进行操作写入文本,并正确的读取出来
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
//创建一个文本并向里面输入内容
ofstream OutputFile("test.txt");//创建一个txt文本
OutputFile << "hello meimei\n";//输入文本内容
OutputFile << "hello shuige";
OutputFile.close();//关闭文件
//开始读取数据,这个情况的读取文件是全部进行读取
char buffer[256];
ifstream in("test.txt");
if (!in.is_open())
{
cout << "Error opening file"; exit(1);
}
while (!in.eof())
{
in.getline(buffer, 100);//每行进行读取
cout << buffer << endl;
}
while (1);
return 0;
}