繁体   English   中英

在C中逐个字符打印文件(任何长度)

[英]Print file (of any length) character by character in C

有没有一种方法可以逐个字符地打印整个文件,而无需知道它的长度或担心它有多少行?

现在,我读取一个文件并计算它有多少行,读取每一行,并将其发送到操作函数,以打印出操作过的字符串。 为此,我必须创建一个countLines()函数和一个readLine()函数。 只是想知道是否还有更有效的方法。

这样的事情应该做:

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

为什么不使用fread。 这是一个例子:

/* 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;
}

注意:缓冲区保存文件的内容。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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