c++读文件怎么换行?
假如一个文件内容是
1 2 3
4 5 6
7 8 9
怎么把1 4 7 读出来?
c++写文件怎么换行?
就是你先写了一串信息了然后你想之后写的东西可以跳到文件下一行记录
是直接用endl吗?
比如
fstream outfile;
outfile("d::\text",ios::out);
int a=1,b=2,c=3;
outfile<<a<<endl;
outfile<<b<<endl;
outfile<<c<<endl;这样吗?
c++用fstream类不就可以了吗!
int main()
{
std::fstream outfile;
outfile.open("test.txt",std::ios::app);//向已有文件末尾添加内容,不会覆盖原有内容
if (!outfile)
{
std::cout << "error";
return -1;
}
outfile << "aaa" << "\n"; //向文件中写入内容,换行方式1
outfile << "ccc" << std::endl;//向文件中写入内容,换行方式2
outfile.close();//关闭文件
// 下面是逐行读取某个文件的内容
outfile.open("test.txt");
std::string str;
std::vector<char> dstChar;//记录所有想要输出的字符,不用特别存储的话可以去掉改行
while (std::getline(outfile, str))//按行读取
{
;//读取一行
if (str=="")
{
std::cout << "NULL"; // 读取到空行的处理
}
else
{
dstChar.push_back(str.at(0));// 将当前行的首字符存入
std::cout << str.at(0) << std::endl;// 答应当前行的首字符
std::cout << str << std::endl;//打印整行内容
}
}
outfile.close();
return 0;
}
c++的库不经常使用。
使用C的方式是
FILE * fp = fopen("d:\\test","wb");
if(fp)
{
fprintf(fp,"%d\r\n",a);
fprintf(fp,"%d\r\n",b);
fprintf(fp,"%d\r\n",c);
fclose(fp);
}
读取和输出。代码如下:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream inFile("d:\\test\\in.txt", ios::in);
int arr[3];
int a, b, c;
for (int j = 0; j < 3; j++)
{
inFile >> arr[0];
if (j == 0)
{
a = arr[0];
}
else if (j == 1)
{
b = arr[0];
}
else if (j == 2)
{
c = arr[0];
}
inFile >> arr[1];
inFile >> arr[2];
}
fstream outFile("d:\\test\\out.txt", ios::out);
outFile << a << endl;
outFile << b << endl;
outFile << c << endl;
return 0;
}
fread fwrite?
c++用fstream类里面有写入文件换行的接口 调用就行
fstream里面有函数可以忽略字符