【发布时间】:2017-01-13 02:24:40
【问题描述】:
我想在一行的第一个字符不是“”时读取一个大文件。 但是我写的代码很慢。我怎样才能加快例行程序? 有没有比 getline 更好的解决方案?
void readString(const char *fn)
{
FILE *fp;
char *vString;
struct stat fdstat;
int stat_res;
stat_res = stat(fn, &fdstat);
fp = fopen(fn, "r+b");
if (fp && !stat_res)
{
vString = (char *)calloc(fdstat.st_size + 1, sizeof(char));
int dataEnd = 1;
size_t len = 0;
int emptyLine = 1;
char **linePtr = malloc(sizeof(char*));
*linePtr = NULL;
while(dataEnd)
{
// Check every line
getline(linePtr, &len, fp);
// When data ends, the line begins with space (" ")
if(*linePtr[0] == 0x20)
emptyLine = 0;
// If line begins with space, stop writing
if(emptyLine)
strcat(vString, *linePtr);
else
dataEnd = 0;
}
strcat(vString, "\0");
free(linePtr);
linePtr = NULL;
}
}
int main(int argc, char **argv){
readString(argv[1]);
return EXIT_SUCCESS;
}
【问题讨论】:
-
calloc=malloc+memset(..., 0, ...)一步到位。 -
而
malloc(0)没有返回size_t的有效地址,请按照getline 手册中所述从堆栈传递一个变量:size_t len = 0;...getline(&line, &len, stream) -
谢谢!我已经修好了..但这并没有加快我的代码速度;)
-
当你调用getline时,你需要传入一个缓冲区的地址,以及一个保存该缓冲区长度的size_t的地址。像这样的东西: char *buf = malloc(numberOfBytes); size_t bufsize = numberOfBytes; getline(&buf, &bufsize, f);
-
您可以尝试将
mmap()与文件一起使用,然后不需要将其读入内存。
标签: c performance file stream getline