简单的 C 语言文件读写程序






1.16/5 (13投票s)
2007年11月14日
3分钟阅读

45080

619
一个用于在文件中读取、写入和查找记录的程序。
引言
在 C 语言中,从磁盘文件到打印机的所有东西都是文件。 在本程序中,我将解释如何在一个给定的文件中导航,并根据各种类别查找所需的数据。
打开文件
FILE *fp; /* create a pointer to the file */ i = 0; /* open the file*/ if((fp = fopen(FILE_NAME, "r")) == NULL) { perror("Could not open the file."); exit(1); }
关闭文件使用 fclose() 函数关闭文件,该函数定义为 int fclose(FILE *fp);。 fclose(fp); /* close the file*/
|
选择要显示的记录
从文件读取的数据将存储在一个结构中。 ShowRecords 函数将引用该结构以打印结果。
/*show records by reading*/ void show_records_by_rating(const char* rating, struct record* data) { int found = 0; int i; int data_rating = atoi(rating); struct record struct_result[FILE_SIZE]; printf("\n"); for(i = 0; i< struct_size; i++) { if(data[i].rating == data_rating) { printf("%s %s %f %d\n", data[i].site, data[i].date, data[i].reading, data[i].rating ); strcpy(struct_result[i].site, data[i].site); strcpy(struct_result[i].date, data[i].date); struct_result[i].reading = data[i].reading; struct_result[i].rating = data[i].rating; found++; } } save_results(found, struct_result); }
保存结果
通过指定文件名可以保存查看的结果。 结果将使用 sprintf 函数写入磁盘。
void save_results(int found, struct record *data) { char res; char response; char file_name ; char line ; int i; FILE *fp; (found>0) ? printf("%d records found.\n", found) : printf("No records found\n"); if(found>0) { printf("\nSave the records? [Y/N]"); scanf("%s", response); res = toupper(response[0]); if(res == 'Y') { printf("\nEnter the file name : "); scanf("%s", file_name); fp = fopen ( file_name , "a" ); for(i = 1; i< found+1; i++) { sprintf(line, "%s %s %f %d\n", data[i].site, data[i].date, data[i].reading, data[i].rating); fprintf(fp, line, file_name); } fclose (fp); } } }
关注点
在 C 语言中读写文件不如 Java 或 C# 等高级语言那么容易,它们提供了专门的方法,但 C 编译器为非托管 Win32 或 UNIX 环境生成高效的代码。
历史
- 创建日期:2007 年 11 月 15 日