reading a string from a file

前端 未结 4 633
Happy的楠姐
Happy的楠姐 2021-01-06 04:03

I have one text file. I have to read one string from the text file. I am using c code. can any body help ?

4条回答
  •  不思量自难忘°
    2021-01-06 04:47

    This should work, it will read a whole line (it's not quite clear what you mean by "string"):

    #include 
    #include 
    
    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;
    }
    

    The return value is 1 if all went well, 0 on error.

    Since this uses a plain fgets(), it will retain the '\n' line feed at the end of the line (if present).

提交回复
热议问题