C语言 在 C 中一次读取一行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2372813/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 04:43:47  来源:igfitidea点击:

Reading one line at a time in C

cfile

提问by Mahesh Gupta

Which method can be used to read one line at a time from a file in C?

哪种方法可用于从 C 中的文件一次读取一行?

I am using the fgetsfunction, but it's not working. It's reading the space separated token only.

我正在使用fgets函数,但它不起作用。它只读取空格分隔的标记。

What to do?

该怎么办?

回答by rekha_sri

Use the following program for getting the line by line from a file.

使用以下程序从文件中逐行获取。

#include <stdio.h>
int main ( void )
{
  char filename[] = "file.txt";
  FILE *file = fopen ( filename, "r" );

  if (file != NULL) {
    char line [1000];
    while(fgets(line,sizeof line,file)!= NULL) /* read a line from a file */ {
      fprintf(stdout,"%s",line); //print the file contents on stdout.
    }

    fclose(file);
  }
  else {
    perror(filename); //print the error message on stderr.
  }

  return 0;
}

回答by LukeN

This should work, when you can't use fgets()for some reason.

当您fgets()由于某种原因无法使用时,这应该有效。

int readline(FILE *f, char *buffer, size_t len)
{
   char c; 
   int i;

   memset(buffer, 0, len);

   for (i = 0; i < len; i++)
   {   
      int c = fgetc(f); 

      if (!feof(f)) 
      {   
         if (c == '\r')
            buffer[i] = 0;
         else if (c == '\n')
         {   
            buffer[i] = 0;

            return i+1;
         }   
         else
            buffer[i] = c; 
      }   
      else
      {   
         //fprintf(stderr, "read_line(): recv returned %d\n", c);
         return -1; 
      }   
   }   

   return -1; 
}

回答by Ant

If you are coding for a platform that has the GNU C library available, you can use getline():

如果您正在为具有可用 GNU C 库的平台编码,则可以使用 getline():

http://www.gnu.org/s/libc/manual/html_node/Line-Input.html

http://www.gnu.org/s/libc/manual/html_node/Line-Input.html

回答by JaredPar

The fgetsfunction will read a single line from a file or numcharacters where numis the second parameter passed to fgets. Are you passing a big enough number to read the line?

fgets函数将从文件或num字符中读取一行,其中num第二个参数是传递给fgets. 您是否传递了足够大的数字来阅读该行?

For Example

例如

// Reads 500 characters or 1 line, whichever is shorter
char c[500];
fgets(c, 500, pFile);

Vs.

对比

// Reads at most 1 character
char c;
fgets(&c,1,pFile);

回答by Mike Yam

This is more of a comment than a complete answer, but I don't have enough points to comment. :)

这与其说是一个完整的答案,不如说是一个评论,但我没有足够的观点来评论。:)

Here's the function prototype for fgets():

这是 fgets() 的函数原型:

char *fgets(char *restrict s, int n, FILE *restrict stream);

It will read n-1 bytes or up to a newline or eof. For more info see here

它将读取 n-1 个字节或最多一个换行符或 eof。有关更多信息,请参见此处

回答by t0mm13b

Use fgetsto read from the line, and then use getc(...)to chew up the newline or end-of-line to continue reading....here's an example of forever reading a line...

用于fgets从行中读取,然后用于getc(...)咀嚼换行符或行尾以继续阅读......这是永远阅读一行的示例......

// Reads 500 characters or 1 line, whichever is shorter
char c[500], chewup;
while (true){
    fgets(c, sizeof(c), pFile);
    if (!feof(pFile)){
        chewup = getc(pFile); // To chew up the newline terminator
        // Do something with C
    }else{
        break; // End of File reached...
    }
}

回答by Andrey

use either fgetsif you know that your lines will fit into buffer or use fgetcfor more control over reading

请使用fgets,如果你知道你的行会放入缓冲区或使用fgetc超过阅读更多的控制

回答by Didier Trosset

fgets()should be the way to go?…

fgets()应该是要走的路?...

回答by Mahesh Gupta

Source of Error:

错误来源:

Actually it was not my fault.. In this case . I was using strtok function and and accidently modified my original my original string. Hence while printing I was getting the error...

其实这不是我的错..在这种情况下。我正在使用 strtok 函数并且不小心修改了我原来的原始字符串。因此,在打印时我收到了错误...

Thanks Everyone for Helping me.. :)

谢谢大家帮助我.. :)

回答by coderboy

You can use fscanf instead of fgets. Because fgets fscanf for characters including spaces but while using fscanf you can separately access to data saved in a file.eg there be a file having name class roll.now declare a string and two integers line.

您可以使用 fscanf 代替 fgets。因为 fgets fscanf 用于包含空格的字符,但是在使用 fscanf 时,您可以单独访问保存在文件中的数据。例如,有一个名称为 roll.now 的文件。现在声明一个字符串和两个整数行。