文件系统

来源:互联网 发布:淘宝跨境电商平台 编辑:程序博客网 时间:2024/06/01 21:31

C语言函数的网址:

www.cplusplus.com  —Reference — C library 


#include <stdio.h>#include <string.h>#include <stdlib.h>int main(int argc, const char * argv[]) {    //write file:    FILE *f = fopen("data.txt", "w");    if (f != NULL) {        fputc('S', f);        fputs("SunSu\n", f);                for (int i =0; i < 100; i++) {            fprintf(f, "Item %d\n",i);        }        fclose(f);    }else{        puts("Can not save file");    }        //read file    FILE * f1 = fopen("data.txt", "r");    if (f1) {        //        char ch = fgetc(f1);        //        printf("%c\n",ch);        //        //        char buf[100];        //        fgets(buf, 6, f1);        //        puts(buf);                //获取文件的长度        FILE*fp;        fp=fopen("data.txt","rb");        fseek(fp,0,SEEK_SET);        fseek(fp,0,SEEK_END);        long longBytes=ftell(fp);// longBytes就是文件的长度        printf("length=%ld\n",longBytes);                //遍历文件内容        char buf1[longBytes];        memset(buf1, 0, longBytes);        for (int i=0; i<longBytes; i++) {            char ch = fgetc(f1);            if (ch != EOF) {//End Of File                buf1[i] = ch;            }else{                break;            }        }        printf("%s\n",buf1);                int a;        fscanf(f1, "Item %d\n",&a);        fscanf(f1, "Item %d\n",&a);        fscanf(f1, "Item %d\n",&a);        printf("Num:%d\n",a);                fclose(f1);    }else{        puts("Can not read");    }    puts("End");        return 0;}


0 0
原创粉丝点击