有没有办法打印整个文件,逐个字符,不知道它的长度或担心它有多少行?打印文件(任意长度)逐字符C
现在我读取一个文件并计算它有多少行,读取每一行,并将其发送到一个操纵函数打印操纵字符串。我必须创建一个countLines()函数和一个readLine()函数来完成此操作。只是想知道是否有更有效的东西。
有没有办法打印整个文件,逐个字符,不知道它的长度或担心它有多少行?打印文件(任意长度)逐字符C
现在我读取一个文件并计算它有多少行,读取每一行,并将其发送到一个操纵函数打印操纵字符串。我必须创建一个countLines()函数和一个readLine()函数来完成此操作。只是想知道是否有更有效的东西。
像这样的东西应该做的:
int ch = 0;
while (ch = fgetc(FILE_POINTER) != EOF) {
doSomething (ch);
}
@Brett Alton:如果你只关心每行的字符,而不是自己的换行符,记住忽略这些字符在读取时的处理('\ n'或'\ r''\ n',具体取决于在文件的格式)。 – gablin 2010-09-25 18:39:00
为什么不使用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;
}
注:缓冲区保存文件的内容。
但是,他确实要求阅读“逐字符”。 – gablin 2010-09-25 18:37:16
你真的必须比这更具体。看起来你想'cat file'(linux)或'type file'(windows)。 – pmg 2010-09-25 17:52:50