假设文件address.txt中已存放3位联系人信息,编写程序,从键盘输入1位联系人信息,序号:4,姓名:小鹿,性别:女,电话号码:15821889977,把该联系人添加到文件里。然后从文件中读出全部信息,并在屏幕上显示。
你将就着用吧, 忘记怎么格式化写入了,就用了笨办法
int main()
{
FILE *fp = NULL;
if (fopen_s(&fp, "address.txt","a+")!=0) //open the file by write
{
printf_s("error");
return -1;
}
else
{
char tempInfo[20];
printf_s("please input the cantact's index:\n");
scanf_s("%s", tempInfo,sizeof(tempInfo));
fputs("\n", fp);
fputs(tempInfo,fp);
printf_s("please input the cantact's name:\n");
scanf_s("%s", tempInfo, sizeof(tempInfo));
fputs(tempInfo, fp);
fputs(" ", fp);
printf_s("please input the cantact's sex:\n");
scanf_s("%s", tempInfo, sizeof(tempInfo));
fputs(tempInfo, fp);
fputs(" ", fp);
printf_s("please input the cantact'TEL:\n");
scanf_s("%s", tempInfo, sizeof(tempInfo));
fputs(tempInfo, fp);
fputs(" ", fp);
}
fclose(fp);
char StrLine[1024];
fopen_s(&fp, "address.txt","r"); //open the file by read
while (!feof(fp))
{
fgets(StrLine, 1024, fp);
printf_s("%s", StrLine);
}
fclose(fp);
return 0;
}