什么是 fread 和 fwrite
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
ptr: 一个指向内存块(大小至少为size * nmemb)的指针
size: 读取元素的大小
nmemb: 读取元素的个数
stream: 字符流指针
size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream);
ptr: 一个指向内存块(大小至少为size * nmemb)的指针
size: 写入元素的大小
nmemb: 写入元素的个数
stream: 字符流指针
fread 和 fwrite 是 C语言 库函数中的接口, 用来读文件和写文件.
写文件
字符串
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
FILE* fp = fopen("./tmp.txt", "w");
if (fp == NULL) {
perror("fopen error");
exit(-1);
}
const char* str = "sock is a good man\n";
fwrite(str, strlen(str), 1, fp);
fclose(fp);
return 0;
}
保存文件(结构体链表…)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct ListNode {
char name[16];
struct ListNode* next;
}ListNode;
...
...
...
void saveFile(ListNode* head) {
if (head == NULL) {
return;
}
// 将修改后的内容保存到新的文件
FILE* fp = fopen("./tmp.txt", "r");
FILE* fpNew = fopen("./tmpNew.txt", "w");
if (fp == NULL || fpNew == NULL) {
perror("fopen error");
exit(-1);
}
ListNode* cur = head;
while (cur != NULL) {
fprintf(fpNew, "%s\n", cur->name);
cur = cur->next;
}
fclose(fp);
fclose(fpNew);
remove("./tmp.txt");
rename("tmp.txt", "./tmpNew.txt");
}
读文件
字符串
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
FILE* fp = fopen("./tmp.txt", "r");
if (fp == NULL) {
perror("fopen error");
exit(-1);
}
char buf[1024] = {0};
fread(buf, 1, 1024, fp);
fclose(fp);
return 0;
}
加载文件(结构体链表…)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct ListNode {
char name[16];
struct ListNode* next;
}ListNode;
...
...
...
void loadFile(ListNode* head) {
if (head == NULL) {
return;
}
FILE* fp = fopen("./tmp.txt", "r");
if (fp == NULL) {
perror("fopen error");
exit(-1);
}
// 将文件的内容写入结构体
ListNode* cur = head;
while (cur != NULL) {
int size = fscanf(fp, "%s", cur->name);
if (size > 0) {
cur = cur->next;
}
if (feof(fp)) {
break;
}
}
fclose(fp);
}
参考文章:
feof()的原理和用法
理解feof与EOF