c++也有相关的文件读取操作:file_system,后续有时间再整理。
#include <stdio.h>
typedef struct Info {
int a;
char b;
float c;
} Info;
int main(int argc, char** argv) {
/* fopen的各种模式:
"r": 只读,文件必须存在; "r+": 读写,文件必须存在;
"w": 只写,文件不存在则创建,存在则清空;"w+": 读写,文件不存在则创建,存在则清空;
"a": 追加,文件不存在则创建; "a+": 读写,文件不存在则创建;
若是操作2进制文件,则在上面的基础上加b, 如"rb" */
//写入一行文本
char str[] = "hello world\n"; //\n是换行
FILE* fp = fopen("test.txt", "a+");
if (!fp) {
printf("open file error!\n");
return -1;
}
fputs(str, fp);
fclose(fp);
//写入2进制数据,一般是结构体
Info info = {1, 'a', 1.0};
fp = fopen("test.bin", "ab+");
if (!fp) {
printf("open file error!\n");
return -1;
}
fwrite(&info, sizeof(info), 1, fp);//参数3表示写入一个结构体
fclose(fp);
//读一行文本,注意buf要够大
char buf[100] = {0};
fp = fopen("test.txt", "r");
if (!fp) {
printf("open file error!\n");
return -1;
}
fgets(buf, sizeof(buf), fp);
fclose(fp);
//读2进制数据
fp = fopen("test.bin", "rb");
fread(buf, sizeof(char), 1, fp); //读一个结构体
fclose(fp); //关闭文件
//循环读取
while(!feof(fp) && !ferror(fp)) {}
}