tags:

views:

52

answers:

2

Is there a way to print an entire file, character by character, without know it's length or worrying about how many lines it has?

Right now I read a file and count how many lines it has, read each line, send it to a manipulation function print the manipulated string out. I had to create a countLines() function and a readLine() function to do so. Just wondering if there is anything more efficient.

+4  A: 

Something like this should do:

int ch = 0;
while ( ch = fgetc(FILE_POINTER) != EOF ) {
    doSomething (ch);
}
Faisal Feroz
@Brett Alton: If you're only concerned about the characters on each line and not the linebreaks themselves, remember to ignore processing of those characters when you read them ('\n' or '\r''\n', depending on the format of the file).
gablin
+1  A: 

Why not use fread. Here is an example:

/* fread example: read a complete file */
#include <stdio.h>
#include <stdlib.h>

int main () {
  FILE * pFile;
  long lSize;
  char * buffer;
  size_t result;

  pFile = fopen ( "myfile.bin" , "rb" );
  if (pFile==NULL) {fputs ("File error",stderr); exit (1);}

  // obtain file size:
  fseek (pFile , 0 , SEEK_END);
  lSize = ftell (pFile);
  rewind (pFile);

  // allocate memory to contain the whole file:
  buffer = (char*) malloc (sizeof(char)*lSize);
  if (buffer == NULL) {fputs ("Memory error",stderr); exit (2);}

  // copy the file into the buffer:
  result = fread (buffer,1,lSize,pFile);
  if (result != lSize) {fputs ("Reading error",stderr); exit (3);}

  /* the whole file is now loaded in the memory buffer. */

  // terminate
  fclose (pFile);
  free (buffer);
  return 0;
}

Note: buffer holds the contents of the file.

Faisal Feroz
But, he did specifically ask to read it "character by character".
gablin