C语言 文本文件字符串的读写方式

  • Post author:
  • Post category:其他


调用fputs函数,把10个字符串输出到文件test.txt中;再从此文件中读入这10个字符串放在一个数组中;最后把字符串数组中的字符串输出到终端屏幕,以检查所有操作的正确性。

要求:

1)10个字符串定义如下:char *str[10]={ “One”,”Two”,”Three”,”Four”,”Five”,”Six”,”Seven”,”Eight”,”Nine”,”Ten”};

2)读取后输出每个字符串一行。

运行参考示例:

One

Two

Three

Four

Five

Six

Seven

Eight

Nine

Ten

运行代码如下:

#include<stdio.h>
#include<stdlib.h>
 
int main()
{
   FILE *fp;
   char *str[10]={ "One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten"};
   char str2[10][20];
   int i;
   
   fp=fopen("test.txt","w");
   if(fp==NULL)
   {
      printf("Can not open write file\n");
      exit(0);
   }
   
   for(i=0;i<10;i++)
   {
      fputs(str[i],fp);
      fputs("\n",fp);
   }
   fclose(fp);
   
   fp=fopen("test.txt","r");
   if(fp==NULL)
   {
      printf("Can not open read file\n");
      exit(0);
   }
   
   i=0;
   while(i<10&&!feof(fp))
   {
      printf("%s",fgets(str2[i],20,fp));
      i++;
   }   
   fclose(fp);
   return 0;
}



版权声明:本文为weixin_74287172原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。