C语言文件操作

 

#include <stdio.h>
#include <stdlib.h>

int main()
{
   FILE * fp, *efp;
    char filePath[]="C:\\Users\\zxf\\Desktop\\文件操作\\file.txt";
   char name[50], oneLine[1024];
   int i, number;

   fp = fopen (filePath, "w+");//清空原有内容打开
   for(i=0;i<3;i++){
        gets(name);
        fprintf(fp, "%s\n", name);
   }
   fclose(fp);

    //添加到文件末尾
   fp = fopen (filePath, "rt+");//可读写,不清空原有内容
   fseek(fp, 0, SEEK_END);//指针标记到文件最后
   fprintf(fp, "%s %s %s %d\n", "We", "are", "in", 2014);
   fclose(fp);

     //
    number=0;
    fp=fopen(filePath,"rt+");
    while(!feof(fp)){
        fgets(oneLine, 1024, fp);
        number=number+1;
    }
    fclose(fp);

    i=0;
   fp = fopen (filePath, "rt+");

   while(!feof(fp)){
        fgets(oneLine, 1024, fp);
        printf("%d\t%s",i, oneLine);
        i=i+1;
        if(i+1==number)break;
   }
   fclose(fp);
//    //从文件中指定删除一行
//   fp = fopen (filePath, "rt+");
//   fseek(fp, 0, SEEK_END);
//   fprintf(fp, "%s %s %s %d\n", "We", "are", "in", 2014);
//   fclose(fp);
//
   return(0);
}

 

posted @ 2014-04-12 22:09  偶尔会寂寞  阅读(156)  评论(0编辑  收藏  举报