簡體   English   中英

如何編寫一個ANSI C用戶定義函數以從文本文件返回特定行?

[英]How to write a ANSI C user-defined function that returns a specific line from a text file?

如何編寫一個ANSI C用戶定義函數以從文本文件返回特定行?

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

這應該可以解決問題:

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);
  }

}

編輯:建議采用的邊界條件caflorenzog的評論已被列入。 從未想到過防錯可能是如此乏味! (仍然不檢查行號超過int可以安全容納的情況。這是OP的練習:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM