开发者

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

开发者 https://www.devze.com 2023-01-18 02:21 出处:网络
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?

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() fu开发者_JAVA技巧nction 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消