C++文件读写
# iostream 读二进制
//打开文件
string fileName = "test.dat"
fstream readFile;
readFile.open(fileName, ios::binary | ios::in);
if (!readFile.is_open())
{
cout << "cannot open file : " << fileName << endl;
//处理打开失败的情况。 这里没找到失败原因如何打印。
}
//读数据
struct stData stdata;
while (readFile.peek() != EOF)
{
readFile.read((char*)&stdata,sizeof(stdata));
if (readFile.gcount() < sizeof(stdata)) {
cout << "the last data is not complete." << endl;
break;
}
//处理数据
}
//关闭文件
readFile.close();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# FILE* 读
//打开文件
FILE* readFile;
errno_t err;
string readFileName = "test.dat";
int err = fopen_s(&readFile, readFileName.c_str(), "rb");//r表示read,b表示二进制
//检查打开错误信息
char errmsg[64];
if (err != 0) {
strerror_s(errmsg, 64, err);
cout << "cannot open file '" << readFileName <<"' : "<< errmsg <<endl;
continue;
}
//读数据
struct stData *st = new stData[10];
int readNum=0;
readNum = fread(&st, sizeof(st), 10, readFile);//从readFile中读取10个stData,返回读成功的个数。
//关闭文件
fclose(readFile);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# FILE* 写
//打开文件
FILE* writeFile;
string writeFileName = "test.txt";
int err = fopen_s(&writeFile, writeFileName.c_str(), "w");
//检查打开写文件的错误信息
char errmsg[64];
if (err != 0) {
strerror_s(errmsg, 64, err);
cout << "cannot open write file '" << writeFileName <<"' : "<< errmsg <<endl;
continue;
}
//写入
fprintf(writeFile, "write someting to file %d.\n", 123);
//关闭文件
fclose(writeFile);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
编辑 (opens new window)
上次更新: 2023/05/07, 17:27:54