fread()和fwrite()
Created|Updated
|Post Views:
了解
这两个函数是以二进制形式处理数据中,不同于其他I/O函数,是以文本形式处理。
函数
fread()
参数:
(地址,数据块,数据块个数,文件指针)
返回值:
两种情况:1.返回文件中成功读取项的数量。2.遇到文件结尾返回0
fwrite()
- 参数
(地址,数据块,数据块的个数,文件指针)
示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| #include<stdio.h> #include<stdlib.h> #define SIZE 256 int main(int argc, char *argv[]) { FILE *in, *out; int bytes; char temp[SIZE];
if (argc != 3) { fprintf(stderr, "Usage: %s filename\n", argv[0]); exit(EXIT_FAILURE); } if ((in = fopen(argv[1], "r")) == NULL) { fprintf(stderr, "I couldn't open the file \"%s\"\n", argv[1]); exit(EXIT_FAILURE); } if ((out = fopen(argv[2], "w")) == NULL) { fprintf(stderr, "I couldn't open the file \"%s\"\n", argv[2]); exit(EXIT_FAILURE); } while ((bytes = fread(temp, sizeof(char), 256, in)) > 0) { fwrite(temp, sizeof(char), bytes, out); } fclose(in); fclose(out); return 0; }
|
将结构保存到文件1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
| #include<stdio.h> #include<stdlib.h> #include<string.h> #define MAXTITL 40 #define MAXAUTL 40 #define MAXBKS 10 char * s_gets(char * st, int n); struct book { char title[MAXTITL]; char author[MAXAUTL]; float value; };
int main() { struct book library[MAXBKS]; int count = 0; int index, filecount; FILE * pbooks; int size = sizeof(struct book); if((pbooks = fopen("book.dat", "a+b")) == NULL) { fputs("Can't open book.dat file\n", stderr); exit(1); } rewind(pbooks); while (count < MAXBKS && fread(&library[count], size, 1, pbooks) == 1) { if(count == 0) puts("Curren contents of book.dat:"); printf("%s by %s: $%.2f\n", library[count].title, library[count].author, library[count].value); count++; } filecount = count; if (count == MAXBKS) { fputs("The book.dat file is full.", stderr); exit(2); } puts("Plese add new book titles."); puts("Press [enter] at the start of a line to stop."); while (count < MAXBKS && s_gets(library[count].title, MAXTITL) != NULL && library[count].title[0] != '\0') { puts("Now enter the author."); s_gets(library[count].author, MAXAUTL); puts("Now enter the value"); scanf("%f", &library[count++].value); while (getchar() != '\n') continue; if (count < MAXBKS) puts("Enter the next title."); }
if(count > 0) { puts("Here is the list of your books:"); for(index = 0; index < count; index++) printf("%s by %s: %.2f\n", library[index].title, library[index].author ,library[index].value); fwrite(&library[filecount], size, count - filecount, pbooks); } else puts("No books? Too bad.\n"); puts("Bye.\n"); fclose(pbooks); return 0; }
char * s_gets(char * st, int n) { char * ret_val; char * find; ret_val = fgets(st, n, stdin); if(ret_val) { find = strchr(st, '\n'); if (find) *find = '\0'; else while (getchar() != '\n') continue; } return ret_val; }
|