C 语言文件操作

1.文件读写

 1 #include <stdio.h>
 2 #include <string.h>
 3 
 4 int main() {
 5 
 6 
 7     //write file
 8 //    FILE *f = fopen("data.txt", "w");
 9 //    if (f != NULL) {
10 //        fputs("Hello C!\n", f);//字符串
11 //        fputc('A', f);//字符
12 //        fclose(f);
13 //    } else {
14 //        puts("Can not save file");
15 //    }
16 //    puts("End");
17 
18 
19 
20 
21     //read file
22     FILE *file = fopen("data.txt", "r");
23     if (file) {
24 
25         //读取字符
26 //        char ch = fgetc(file);
27 //        printf("%c\n", ch);
28 
29         //读取字符串
30 //        char buf[100];
31 //        fgets(buf, 5, file);
32 //        puts(buf);
33 
34         char buf[100];
35         memset(buf, 0, 100);
36         for (int i = 0; i < 100; ++i) {
37             char ch = fgetc(file);
38             if (ch != EOF) {
39                 buf[i] = ch;
40             } else {
41                 break;
42             }
43         }
44         printf("%s\n", buf);
45         fclose(file);
46     } else {
47         puts("Can not read file");
48     }
49     return 0;
50 }

 

 

2.格式化读写

 1 #include <stdio.h>
 2 #include <string.h>
 3 
 4 int main() {
 5     //write
 6 //    FILE *f = fopen("data.txt", "w");
 7 //    if (f) {
 8 //        for (int i = 0; i < 100; ++i) {
 9 //            fprintf(f, "Item %d\n", i);
10 //        }
11 //        fclose(f);
12 //    } else {
13 //        puts("Can not save file");
14 //    }
15 //    puts("End");
16 
17     //read
18     FILE *f = fopen("data.txt", "r");
19     if (f) {
20 
21         //读一行
22 //        int a;
23 //        fscanf(f,"Item %d\n",&a);
24 //        printf("Num read is %d\n",a);
25 
26         //读取数字
27 //        for (int i = 0; i <100 ; ++i) {
28 //            fscanf(f,"Item %d\n",&i);
29 //            printf("Num read is %d\n",i);
30 //        }
31 
32 
33         //同时读取
34         char a[100];
35         memset(a, 0, 100);
36         for (int i = 0; i < 100; ++i) {
37             fscanf(f, "%s %d\n", &a, &i);
38             printf("%s %d\n", a, i);
39         }
40 
41 
42         fclose(f);
43     } else {
44         puts("Can not read file");
45     }
46     return 0;
47 }

 

posted @ 2016-12-20 17:05  changchou  阅读(207)  评论(0编辑  收藏  举报