Explica principalmente la programación de archivos mediante el acceso a la lista vinculada de la libreta de direcciones.
ARCHIVO *fopen(const char *ruta, const char *modo);
const char *ruta ruta del archivo
const char *modo método de apertura o con qué permisos
Abra el archivo antes de leerlo y escribirlo.El campo minado aquí es que el formato de lectura debe ser estrictamente consistente con el de escritura, de lo contrario es extremadamente fácil cometer errores.
fscanf(file,"%s%s",newnode->num,newnode->name);
fprintf(file2,"%-11s %-15s\r\n",head->next->num,head->next->name);
Eche un vistazo al código principal de lectura y escritura por separado.
Aquí utilizo un bucle while para colocar la información leída en la lista vinculada en forma de nodos.
Agregar:
E/S sin caché: leer, escribir, abrir...
E/S estándar (en caché): fgets, fread, fwrite...
Si utilizamos directamente E/S no almacenadas en caché para leer y escribir en el búfer del kernel, causará muchos problemas causados por una mala gestión (como demasiadas escrituras a la vez o ineficiencia causada por múltiples llamadas al sistema).
La E/S estándar (en caché) nos resuelve estos problemas: maneja muchos detalles, como la asignación del búfer, la realización de E/S con longitud optimizada, etc., lo que nos facilita su uso.
Referencia específica: IO sin búfer y IO con búfer: de novato a novato - Blog de CSDN https://blog.csdn.net/carolzhang8406/article/details/7227761
int fscanf_file(Linker *head)
{
int flag;
Linker *newnode,*p;
p = head;
FILE *file = fopen("./addressbook.txt","r");
if(NULL == file)
{
perror("fopen file");
return F;
}
fscanf(file,"%d",&flag);
while(flag != 0) //用尾插的方式放入读取的数据
{
p = head;
newnode = (Linker *)malloc(sizeof(struct link)); //申请节点把读取的信息逐条放入
if (newnode == NULL)
{
return F;
}
while(p->next != NULL)
{
p=p->next;
}
fscanf(file,"%s%s",newnode->num,newnode->name);
fscanf(file,"%d",&flag); //读取每条信息编号
newnode->next = NULL;
p->next = newnode;
}
fclose(file);
return T;
}
int fprint_file(Linker *head)
{
int k = 1;
FILE *file2 = fopen("./addressbook.txt","w+");//每次重新写入信息
{
if(file2 == NULL)
{
perror("fopen file2");
exit(2);
}
}
while(head->next != NULL)
{
fprintf(file2, "%d ",k++); //为联系人编号
fprintf(file2,"%-11s %-15s\r\n"
,head->next->num,head->next->name);
head = head->next;
}
fprintf(file2, "%d\n",0);//标志位,如果只有0,没有联系人
fclose(file2);
return T;
}
La siguiente es una libreta de direcciones muy sencilla para ayudar a comprender y utilizar
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define T 1
#define F 0
typedef struct link
{
char num[15]; //学号
char name[30]; //姓名
struct link *next;
}Linker;
int fscanf_file(Linker *head); //从文件夹读取信息
int fprint_file(Linker *head); //把信息打印到文件
int insert_tail(Linker *head); //插入联系人
int init(Linker **head); //初始化
void print(Linker *head); //显示
int main()
{
Linker *head;
init(&head);
fscanf_file(head);
insert_tail(head);
fprint_file(head);
print(head);
return 0;
}
int init(Linker **head)
{
Linker *newnode = (Linker *)malloc(sizeof(struct link));
if (newnode == NULL)
{
return F;
}
newnode->next = NULL;
*head = newnode;
return T;
}
void print(Linker *head)
{
int i = 0;
if (head->next == NULL)
{
printf("无联系人信息!\n");
}
else
{
printf("\n\n");
printf("联系人信息:\n\n");
while(head->next != NULL)
{
printf("学号:%-11s 姓名:%-15s\n"
,head->next->num,head->next->name);
head = head->next;
i++;
}
printf("\n共有%d人\n",i);
}
}
int insert_tail(Linker *head)
{
Linker *p = head;
Linker *q = head;
int i;
Linker *newnode = (Linker *)malloc(sizeof(struct link));
if (newnode == NULL)
{
return F;
}
while(p->next != NULL)
{
p = p->next;
}
printf("\n请输入新建联系人的学号:\n");
scanf("%s",newnode->num);
while(strlen(newnode->num) != 11)
{
printf("请重新输入新建联系人的学号:\n");
scanf("%s",newnode->num);
}
printf("\n请输入新建联系人的姓名:\n");
scanf("%s",newnode->name);
newnode->next = NULL;
p->next = newnode;
printf("\n*****************添加联系人成功!********************\n");
return T;
}
int fscanf_file(Linker *head)
{
int flag;
Linker *newnode,*p;
p = head;
FILE *file = fopen("./addressbook.txt","r");
if(NULL == file)
{
perror("fopen file");
return F;
}
fscanf(file,"%d",&flag);
while(flag != 0)
{
p = head;
newnode = (Linker *)malloc(sizeof(struct link));
if (newnode == NULL)
{
return F;
}
while(p->next != NULL)
{
p=p->next;
}
fscanf(file,"%s%s",newnode->num,newnode->name);
fscanf(file,"%d",&flag);
newnode->next = NULL;
p->next = newnode;
}
fclose(file);
return T;
}
int fprint_file(Linker *head)
{
int k = 1;
FILE *file2 = fopen("./addressbook.txt","w+");//每次重新写入信息
{
if(file2 == NULL)
{
perror("fopen file2");
exit(2);
}
}
while(head->next != NULL)
{
fprintf(file2, "%d ",k++); //为联系人编号
fprintf(file2,"%-11s %-15s\r\n"
,head->next->num,head->next->name);
head = head->next;
}
fprintf(file2, "%d\n",0);//标志位,如果只有0,没有联系人
fclose(file2);
return T;
}