读写文件
C++读写文件
void readFile()
{
//---------- 打开文件文件
// 文件流类
// 变量名
// 文件地址
/*-------------------------------------
文件模式
in ---- 读
out ---- 写
app ---- 写入到文件尾
ate ---- 打开文件定位到文件尾
trunc ---- 打开时清空文件流
binary ---- 二进制打开
【组合类型】
out | app 写入末尾
out | trunc
in | out 读写
in | out | trunc 读写,并删除文件中已有数据
-----------------------------------------*/
/*
//等价于
ifstream infile;
infile.open("E:/CC++Code/user.csv", ofstream::in | ofstream::trunc);
*/
ifstream infile("E:/CC++Code/user.csv", ofstream::in);
if (!infile)
{
cerr << "open file to be error!!";
return;
}
string str;
// 读取一行数据
while (getline(infile, str))
{
cout<<str<<endl;
}
// 关闭文件
infile.close();
}
void writeFile()
{
//打开文件,执行写操作,并在末尾写入
ofstream outfile("E:/CC++Code/123.csv",ofstream::out | ofstream::app);
// 写入数据,并换行
outfile << "input first" << endl;
outfile << "input seconds" <<endl;
outfile.close();
}
C语言---- 读写文件
void readFile()
{
FILE *inFile = fopen("E:/CC++Code/user.csv", "r+");
char str[maxBuff] = "";
while (!feof(inFile))
{
// 防止文件中读不出数据,导致数据重复
memset(str, 0, maxBuff);
//读取 指定 大小数据; 看做读取一行
fgets(str, maxBuff,inFile);
printf("%s", str);
}
fclose(inFile);
}
void writeFile()
{
FILE *outFile = fopen("E:/CC++Code/123.csv", "a+");
char str[maxBuff] = "frist num 1\n";
char str1[maxBuff] = "second num 2\n";
fwrite(str, strlen(str), 1, outFile);
fwrite(str1, strlen(str), 1, outFile);
fclose(outFile);
}
浙公网安备 33010602011771号