C语言笔记——处理文件03

来源:互联网 发布:我的世界js下载 编辑:程序博客网 时间:2024/06/13 01:07

1.1文件中的位置

C语言在头文件stdio.h中提供了一系列读写外部设备的函数

文件其实是一系列字节,如下图
这里写图片描述

文件有开头和结尾,还有一个当前位置

1.2文件访问

#include<stdio.h>//FILE *fopen(char *name, char *mode);FILE *pfile=fopen("C:\\temp\\myfile.txt","w");//fopen()在<stdio.h>中定义,用来打开文件,将设备映射为文件流//int rename(const char *oldname, const char *newname);//文件重命名rename("C:\\temp\\myfile.txt","C:\\temp\\myfile_copy.txt")fclose(pfile);  //关闭文件fflush(pfile);  //将缓冲区的数据写入文件remove(pfile);  //删除文件

这里写图片描述

注意
文件模式说明是一个带双引号的字符串,而不是单引号中单个字符

1.3写入文本文件

int fputc(int c, FILE *pfile);  //写入文本文件//与putc()相同int mchar;mchar = fgetc(pfile);    //读取文本文件//与getc(pfile)相同//与gets(pfile)不同,从标准输入流中读取一整行输入

程序实现,先写入文件,再读出它

#include <stdio.h>#include <string.h>#include <stdlib.h>const int LENGTH = 80;                /* Maximum input length   */int main(void){  char mystr[LENGTH];                 /* Input string           */  int lstr = 0;                       /* Length of input string */  int mychar = 0;                     /* Character for output   */  FILE *pfile = NULL;                 /* File pointer           */  char *filename = "C:\\myfile.txt";  printf("\nEnter an interesting string of less than 80 characters:\n");  fgets(mystr, LENGTH, stdin);        /* Read in a string       */  /* Create a new file we can write */  if(!(pfile = fopen(filename, "w")))  {    printf("Error opening %s for writing. Program terminated.", filename);    exit(1);  }  lstr = strlen(mystr);  for(int i = lstr-1 ; i >= 0 ; i--)    fputc(mystr[i], pfile);           /* Write string to file backward  */  fclose(pfile);                      /* Close the file                 */  /* Open the file for reading */  if(!(pfile = fopen(filename, "r")))  {    printf("Error opening %s for reading. Program terminated.", filename);    exit(1);  }  /* Read a character from the file and display it */  while((mychar = fgetc(pfile)) != EOF)    putchar(mychar);                  /* Output character from the file */  putchar('\n');                      /* Write newline                  */  fclose(pfile);                      /* Close the file                 */  remove(filename);                   /* Delete the physical file       */  return 0;}

1.4将字符串读写入文本文件

int fputs(char *pstr, FILE *pfile);  //将任意长度字符串写入文本文件中,以“\0”结束,但不写入“\0”fputs("The higher the fewer",pfile);//fput()互补函数*char fgets(char *pstr, int nchar, FILE *pfile);//遇到“\n”或读到nchar-1个字符后时结束,字符“\0”会附到字符串末尾

程序代码段,字符串的读取与写入文本

#include <stdio.h>#include <stdlib.h>#include <stdbool.h>const int LENGTH = 80;                 /* Maximum input length */int main(void){  char *proverbs[] =             {  "Many a mickle makes a muckle.\n",                "Too many cooks spoil the broth.\n",                "He who laughs last didn't get the joke in"                                       " the first place.\n"             };  char more[LENGTH];                   /* Stores a new proverb */  FILE *pfile = NULL;                  /* File pointer         */  char *filename = "C:\\myfile.txt";  /* Create a new file( if myfile.txt does not exist */  if(!(pfile = fopen(filename, "w")))    /* Open the file to write it */  {    printf("Error opening %s for writing. Program terminated.", filename);    exit(1);  }  /* Write our first three sayings to the file. */  int count = sizeof proverbs/sizeof proverbs[0];  for(int i = 0 ; i < count ; i++)    fputs(proverbs[i], pfile);  fclose(pfile);                       /* Close the file */  /* Open the file to append more proverbs */  if(!(pfile = fopen(filename, "a")))  {    printf("Error opening %s for writing. Program terminated.", filename);    exit(1);  }  printf("Enter proverbs of less than 80 characters or press Enter to end:\n");  while(true)  {    fgets(more, LENGTH, stdin);          /* Read a proverb           */    if(more[0] == '\n')                  /* If its empty line        */      break;                             /* end input operation      */    fputs(more, pfile);                  /* Write the new proverb    */  }  fclose(pfile);                         /* Close the file           */  if(!(pfile = fopen(filename, "r")))    /* Open the file to read it */  {    printf("Error opening %s for writing. Program terminated.", filename);    exit(1);  }  /* Read and output the file contents */  printf("The proverbs in the file are:\n\n");  while(fgets(more, LENGTH, pfile))      /* Read a proverb */   printf("%s", more);                   /* and display it */  fclose(pfile);                         /* Close the file */  remove(filename);                      /* and remove it  */  return 0;}

1.5格式化文件的输入输出

#include <stdio.h>#include <stdlib.h>int main(void){  long num1 = 234567L;                       /* Input values...              */  long num2 = 345123L;  long num3 = 789234L;  long num4 = 0L;                            /* Values read from the file... */  long num5 = 0L;  long num6 = 0L;  float fnum = 0.0f;                         /* Value read from the file     */  int   ival[6] = { 0 };                     /* Values read from the file    */  FILE *pfile = NULL;                        /* File pointer                 */  char *filename = "C:\\myfile.txt";  pfile = fopen(filename, "w");                 /* Create file to be written */  if(pfile == NULL)  {    printf("Error opening %s for writing. Program terminated.", filename);    exit(1);  }  fprintf(pfile, "%6ld%6ld%6ld", num1, num2, num3);   /* Write file          */  fclose(pfile);                                      /* Close file          */  printf("\n %6ld %6ld %6ld", num1, num2, num3);   /* Display values written */  pfile = fopen(filename, "r");                       /* Open file to read   */  fscanf(pfile, "%6ld%6ld%6ld", &num4, &num5 ,&num6); /* Read back           */  printf("\n %6ld %6ld %6ld", num4, num5, num6);      /* Display what we got */  rewind(pfile);                          /* Go to the beginning of the file */  fscanf(pfile, "%2d%3d%3d%3d%2d%2d%3f", &ival[0], &ival[1], /* Read it again */                      &ival[2], &ival[3], &ival[4] , &ival[5], &fnum);  fclose(pfile);                                    /* Close the file and    */  remove(filename);                                 /* delete physical file. */  /* Output the results */  printf("\n");  for(int i = 0 ; i < 6 ; i++ )    printf("%sival[i] = %d", i == 4 ? "\n\t" : "\t", i, ival[i]);  printf("\nfnum = %f\n", fnum);  return 0;}
原创粉丝点击