简体   繁体   中英

Print file (of any length) character by character in C

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.

Something like this should do:

int ch = 0;
while ( ch = fgetc(FILE_POINTER) != EOF ) {
    doSomething (ch);
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM