【问题标题】:reading a string from a file从文件中读取字符串
【发布时间】:2019-05-23 03:15:31
【问题描述】:

我有一个文本文件。我必须从文本文件中读取一个字符串。我正在使用c代码。任何身体都可以帮忙吗?

【问题讨论】:

  • 您应该真正尝试并付出一些努力来寻找解决方案,而不是仅仅将其发布在这里期望其他人为您完成工作。另外,让你的问题更清楚。

标签: c


【解决方案1】:

使用fgets从C中的文件中读取字符串。

类似:

#include <stdio.h>

#define BUZZ_SIZE 1024

int main(int argc, char **argv)
{
    char buff[BUZZ_SIZE];
    FILE *f = fopen("f.txt", "r");
    fgets(buff, BUZZ_SIZE, f);
    printf("String read: %s\n", buff);
    fclose(f);
    return 0;
}

为简单起见避免了安全检查。

【讨论】:

    【解决方案2】:
    void read_file(char string[60])
    {
      FILE *fp;
      char filename[20];
      printf("File to open: \n", &filename );
      gets(filename);
      fp = fopen(filename, "r");  /* open file for input */
    
      if (fp)  /* If no error occurred while opening file */
      {           /* input the data from the file. */
        fgets(string, 60, fp); /* read the name from the file */
        string[strlen(string)] = '\0';
        printf("The name read from the file is %s.\n", string );
      }
      else          /* If error occurred, display message. */
      {
        printf("An error occurred while opening the file.\n");
      }
      fclose(fp);  /* close the input file */
    }
    

    【讨论】:

      【解决方案3】:

      这应该可以,它将读取整行(不太清楚您所说的“字符串”是什么意思):

      #include <stdio.h>
      #include <stdlib.h>
      
      int read_line(FILE *in, char *buffer, size_t max)
      {
        return fgets(buffer, max, in) == buffer;
      }
      
      int main(void)
      {
        FILE *in;
        if((in = fopen("foo.txt", "rt")) != NULL)
        {
          char line[256];
      
          if(read_line(in, line, sizeof line))
            printf("read '%s' OK", line);
          else
            printf("read error\n");
          fclose(in);
        }
        return EXIT_SUCCESS;
      }
      

      一切顺利返回1,出错返回0。

      由于它使用普通的 fgets(),它将在行尾保留 '\n' 换行符(如果存在)。

      【讨论】:

      • 你没有在问题中这么说。
      • @user556761 在这里,您想接受人们对您众多问题的回答,提出更清晰的问题,并做一些您自己的工作。
      【解决方案4】:

      这是从文件中获取字符串的简单方法。

      #include<stdio.h>
      #include<stdlib.h>
      #define SIZE 2048
      int main(){
      char read_el[SIZE];
      FILE *fp=fopen("Sample.txt", "r");
      
      if(fp == NULL){
          printf("File Opening Error!!");
      
      }
      while (fgets(read_el, SIZE, fp) != NULL)
          printf(" %s ", read_el);
      fclose(fp);
      return 0;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-01-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多