tags:

views:

70

answers:

1

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

char * ReadFromFile(const char * fileName, int line)
{
    //..........
}
+3  A: 

This should do the trick:

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

}

Edit: The boundary conditions suggested by caf & lorenzog in the comments have been included. Never thought error-proofing could be so tedious! (Still doesn't check for cases where line number is more than int can safely hold. This is left as an exercise to OP :)

Kedar Soparkar
@JMSA, alright, I have added the buffer in the function itself.
Kedar Soparkar
you'd better check that line > 0 or get it as unsigned int. And assume line isn't bigger than the maximum value an int has on that architecture. But I think that what I am pointing out has nothing to do with ansi C, hence I'm just making a comment here.
lorenzog
Perhaps a check for EOF?
caf
check EOF but not fopen()? ;)
Nyan
@Nyan, I have already answered the question; there's no valid reason to my mind why you should go around handing out -1 because the code doesn't check one particular error case; read my remark to OP, for instance.
Kedar Soparkar