• c语言中文件的操作


    所谓“文件”是指一组相关数据的有序集合。这个数据集有一个名称,叫做文件名。实际上在前面的各章中我们已经多次使用了文件,例如源程序文件、目标文件、可执行文件、库文件 (头文件)等。 文件通常是驻留在外部介质(如磁盘等)上的,在使用时才调入内存中来

    例一:读取文件中的内容

    #include<stdio.h>
    
    int main()
    {
      FILE *fp;
      char ch;
      if((fp=fopen("d:\c1.txt","rt"))==NULL)
        {
        printf("
    Cannot open file strike any key exit!");
        getch();
        exit(1);
        }
      ch=fgetc(fp);
    
      while(ch!=EOF) //ch是字符,一个一个的取出来 
      {
        putchar(ch);
        ch=fgetc(fp);//意为从文件指针stream指向的文件中读取一个字符,读取一个字节后,光标位置后移一个字节。 
      }
      fclose(fp);
    }

     例二:写入文件内容

    #include<stdio.h>
    int main()
    {    
      FILE *fp;    
          fp = fopen("aa.txt", "w"); //当前编译器的目录 
          if(fp ==NULL)  
          printf("打开文件aa.txt失败
    "); 
         fprintf(fp, "Hello World2");  
        return 0;
     }

    把12345写入另外一个文件

    #include "stdio.h"
    int main()
    {
        FILE *fp;
        char a[5]={'1','2','3','4','5'};
        int i;
        fp=fopen("f.txt","w");
        for(i=0;i<5;i++)
        fputc(a[i],fp);
       //另外一种方法写入 fprintf(fp,"%c",a[i]);
    fclose(fp);
    return 0; }

    例三:写入1到100到文件

     #include<stdio.h>
    main()
    {int i,j,t;
      FILE *f1;
      f1=fopen("d:\a.txt","w");
      for(i=1;i<100;i++)
      {
              fprintf(f1,"%d
    ",i); 
          
      }  
    }

    例四:写入文件后,又读出文件

     #include<stdio.h>
    main()
    {
      int i,j,t;
      FILE *f1;
      f1=fopen("d:\a.txt","w");
      for(i=1;i<100;i++)
      {
              fprintf(f1,"%d
    ",i);        
      } 
       fclose(f1); //这里要关闭,后面才能读取 
      
      FILE *fp;
      char ch;
      fp=fopen("d:\a.txt","rt"); 
    
      ch=fgetc(fp);
      while(ch!=EOF) //ch是字符,一个一个的取出来 
      {
        putchar(ch);
        ch=fgetc(fp);//意为从文件指针stream指向的文件中读取一个字符,读取一个字节后,光标位置后移一个字节。 
      }
      fclose(fp);
    }
  • 相关阅读:
    [POI2014]FarmCraft
    [POI2014]Solar Panels
    Luogu P2824 [HEOI2016/TJOI2016]排序
    CF903G Yet Another Maxflow Problem
    CF901C Bipartite Segments
    CF749E Inversions After Shuffle
    ARC068C Snuke Line
    BZOJ3747 [POI2015]Kinoman
    SA-IS
    简单字符串
  • 原文地址:https://www.cnblogs.com/bluewelkin/p/4073281.html
Copyright © 2020-2023  润新知