如何编写从文本文件返回特定行的ANSI C用户定义函数?

时间:2010-09-28 19:17:56

标签: c file-io

如何编写从文本文件返回特定行的ANSI C用户定义函数?

char * ReadFromFile(const char * fileName, int line)
{
    //..........
}

1 个答案:

答案 0 :(得分:3)

这应该可以解决问题:

char * ReadFromFile(const char * fileName, int line)
{

  FILE *fp;

  char c;
  char *buffer = malloc( 100 * sizeof(char) );  // change 100 to a suitable value; 
  int buffer_length = 100;                      // eg. max length of line in your file

  int num = 0;

  if(line < 0)   // check for negative  line numbers
  {
    printf("Line number must be 0 or above\n");
    return(NULL);
  }

  if( ( fp = fopen(fileName,"r") ) == NULL )
  {
     printf("File not found");
     return(NULL);
  }

  while(num < line)  // line numbers start from 0
  {
    c = getc(fp);
    if(c == '\n')
    num++;      
  }

  c = getc(fp);

  if(c == EOF)
  {
    printf("Line not found\n");
    fclose(fp);
    return(NULL);
  } 
  else
  {
    ungetc(c,fp);     //push the read character back onto the stream
    fgets(buffer,buffer_length,fp);
    fclose(fp);
    return(buffer);
  }

}

修改caf&amp;评论中包含lorenzog。从来没有想过防错可能会如此乏味! (仍然不检查行号大于int的情况是否可以安全保留。这是OP的练习:)