样例:
const char filename[] = "highscore.raw";
int score = 1088;
FILE *hs;
/* create the file and write the value */
printf("Writing high score: %d\n", score);
hs = fopen(filename, "w");
if (hs == NULL)
{
fprintf(stderr, "Error writing to %s\n", filename);
return(1);
}
fwrite(&score, sizeof(int), 1, hs);
fclose(hs);
/* open the file and read the value */
hs = fopen(filename, "r");
if (hs == NULL)
{
fprintf(stderr, "Error reading from %s\n", filename);
return(1);
}
fread(&score, sizeof(int), 1, hs);
printf("Reading high score: %d\n", score);
fclose(hs);
说明:
1.文件名包括后缀 根据自己需要去修改
2.若在VC中运行,会报错
通过在stdafx.h中最上方添加#define _CRT_SECURE_NO_DEPRECATE解决