我不喜欢只是把一堆代码倒在这里,然后让别人为我调试,但我在C语言方面有点缺乏经验,完全被卡住了。
总体目标是对一个非常大的日志文件(11G+)进行清理,我每次读取2048个字节,然后扫描每行,在写入输出文件。最初我使用strstr查找行末,但我发现在读缓冲区末尾的部分行时,它无法工作-我认为这是因为我从文件中读取的“字符串”没有\0结尾,导致strstr混淆了。
所以,经过一番搜索,我想尝试memmem,它似乎是strstr的“二进制安全”替代品。这就是我的问题所在,当调用memmem时,我的程序会崩溃(segmentation fault)。
总体目标是对一个非常大的日志文件(11G+)进行清理,我每次读取2048个字节,然后扫描每行,在写入输出文件。最初我使用strstr查找行末,但我发现在读缓冲区末尾的部分行时,它无法工作-我认为这是因为我从文件中读取的“字符串”没有\0结尾,导致strstr混淆了。
所以,经过一番搜索,我想尝试memmem,它似乎是strstr的“二进制安全”替代品。这就是我的问题所在,当调用memmem时,我的程序会崩溃(segmentation fault)。
#include <stdio.h>
#include <string.h>
#define BUFF_LEN 2048
int main (void)
{
char file_buff[BUFF_LEN], prev_line[BUFF_LEN], curr_line[BUFF_LEN];
char *p_line_start, *p_lf;
int bytes_consumed, bytes_read;
FILE *in_fp, *out_fp;
in_fp = fopen("208.log", "r");
out_fp = fopen("expanded.log", "w+");
int sane = 0;
while (1) {
bytes_read = fread(file_buff, 1, BUFF_LEN, in_fp);
if (bytes_read == 0) {
break;
}
// Set the pointer to the beginning of the file buffer
p_line_start = file_buff;
bytes_consumed = 0;
// Chomp lines
while (bytes_consumed < bytes_read) {
printf("Read to go with bytes_read = %d, bytes_consumed = %d\n",
bytes_read, bytes_consumed);
p_lf = (char *) memmem(p_line_start, bytes_read - bytes_consumed,
"\n", 1);
if (p_lf == NULL) {
// No newline left in file_buff, store what's left in
// curr_line and break out to read more from the file.
printf("At loop exit I have chomped %ld of %d\n",
p_line_start - file_buff, bytes_read);
//break;
goto cleanup;
}
// Copy the line to our current line buffer (including the newline)
memcpy(curr_line, p_line_start, p_lf - p_line_start + 1);
printf("Chomped a line of length %ld\n", p_lf - p_line_start + 1);
fwrite(curr_line, 1, p_lf - p_line_start + 1, out_fp);
p_line_start = p_lf + 1;
bytes_consumed += p_lf - p_line_start + 1;
}
有人能给我支个招吗?!
欢迎提供如何更好地自行调试的技巧。
fread
而不是fgets
读取文件,使事情变得过于复杂。当然,在使用fgets
时,你可能仍需要处理行截断。输入文件中最长的行有多长?或者这是未知的? - user3386109fread
和fgets
之间的主要性能差异。至于最长的行,有一个5MB的行缓冲区并不算不合理,例如char *buffer = malloc(5000000); while (fread(buffer,5000000,fp_in)!=NULL){...}
那么我的问题是,您是否预期日志文件将具有超过5MB的行? - user3386109