文件输入输出 c语言

c语言使用fopen(const char* fileName, const char* mode);返回对应文件的指针FILE*

文件不存在 是否可读 如何写入
“r” 出错 不可泄
“w” 创建 清空后写入
“a” 创建 追加写入
“r+” 出错 覆盖式写入
“w+” 创建 清空后写入
“a+” 创建 追加写入
1
2
3
4
5
FILE* file = fopen("test", "a+");
if (file == NULL) {
cout << "open file failed" << endl;
return 1;
}

打开文件后可以使用fscanf来读取文件的数据 fscanf(file, "%d %d", &a, &b);

或用fprintf来向文件写入数据 fprintf(file, "%d\n", a + b);

第一个参数需要传入文件的指针

char ch = fgetc(file); fputc(ch, file);获取和输出单个字符

fgets(str, 100, file); fputs(str, file); 来读入和输出整行的字符串

使用完文件后 调用fclose(file);进行关闭

文件输入输出 c++

在头文件 <fstream>中 通过fstream类型来定义文件流

fstream fio("text.txt", ios::in | ios::out | ios::app);

其中in代表读入 out代表清空后写入 app是append的缩写,代表追加,多个模式相加使用|

1
2
3
4
5
6
7
fstream fio("text.txt", ios::in | ios::out | ios::app);
fio >> a >> b;
fio << a << b;
ifstream fin("test.txt", ios::in);
ofstream fout("test.txt", ios::app);
fin >> a >> b;
fout << a << b;

fio.close(), fin.close(), fout.close();进行关闭

在头文件<sstream>

1
2
3
4
int a, b;
string str = "1 2";
stringstream ss(str);
ss >> a >> b;