gpt4 book ai didi

c - 如何计算文件中的换行符,但不计算只是换行符的行?

转载 作者:行者123 更新时间:2023-11-30 19:51:28 25 4
gpt4 key购买 nike

为了正确解析输入,我需要能够计算文件中的行数。但是,我不想计算只是换行符的行。为了帮助解决这个问题,我创建了以下函数:

int countLinesInFile(char *filename) {
int newlines = 0;

if (access(filename,F_OK) != -1)
error("File not found",0);

FILE *input = fopen(filename,"r");

int size = 256 * 4;
char buffer[size];
while ((fgets(buffer,sizeof(buffer),input)) != EOF) {
printf("Read a string");
if (buffer == "\n")
continue;
newlines++;
}

fclose(input);
return newlines;
}

在文件顶部,我有以下内容:

#include <stdio.h>
#include <unistd.h>

当我运行程序并尝试计算行数时,它出现段错误。使用 valgrind,我可以看到以下内容:

==6632== Invalid read of size 4
==6632== at 0x4EA8E6B: fgets (in /usr/lib64/libc-2.24.so)
==6632== by 0x402219: countLinesInFile (in [executable])
[other information about program, does not seem relevant]
==6632== Address 0x0 is not stack'd, malloc'd or (recently) free'd
==6632==
==6632==
==6632== Process terminating with default action of signal 11 (SIGSEGV)
==6632== Access not within mapped region at address 0x0
==6632== at 0x4EA8E6B: fgets (in /usr/lib64/libc-2.24.so)
==6632== by 0x402219: countLinesInFile (in [executable])
[other information about program, does not seem relevant]
==6632== If you believe this happened as a result of a stack
==6632== overflow in your program's main thread (unlikely but
==6632== possible), you can try to increase the size of the
==6632== main thread stack using the --main-stacksize= flag.
==6632== The main thread stack size used in this run was 8388608.
==6632==
==6632== HEAP SUMMARY:
==6632== in use at exit: 475 bytes in 16 blocks
==6632== total heap usage: 19 allocs, 3 frees, 3,075 bytes allocated
==6632==
==6632== LEAK SUMMARY:
==6632== definitely lost: 0 bytes in 0 blocks
==6632== indirectly lost: 0 bytes in 0 blocks
==6632== possibly lost: 0 bytes in 0 blocks
==6632== still reachable: 475 bytes in 16 blocks
==6632== suppressed: 0 bytes in 0 blocks
==6632== Rerun with --leak-check=full to see details of leaked memory
==6632==
==6632== For counts of detected and suppressed errors, rerun with: -v
==6632== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)

我试图在 while 循环的开头放置一行“printf("Reading file")”。这段代码不执行,我相信 fgets 是问题所在。不幸的是,我不知道这个问题是什么。

我已验证我尝试读取的文件中确实包含正确的文本,并且不为空。

我创建的函数是该任务的正确方法吗?如果是这样,我可能遇到什么问题?以后如何避免这个问题?

更新:这对我来说确实是一个愚蠢的错误。我正在使用 Valgrind 运行该程序,它看起来没有使用可执行文件的目录,这意味着它找不到该文件。感谢您的帮助。

最佳答案

有两件事:首先,一旦无法读取更多行,fgets 就会返回 NULL,而不是 EOF。因此,条件应该是 while(fgets(...) != NULL) 或短 while(fgets(...))。其次,buffer == "\n"比较两个指针到字符,即比较两个内存地址。而且不太可能有任何东西具有与字符串文字 "\n" 相同的内存地址。因此,比较字符,即 buffer[0]=='\n'buffer[0]!='\n'。我认为您可以轻松地摆脱 continue 语句,使代码如下所示:

  while (fgets(buffer,sizeof(buffer),input)) {
if (buffer[0] != '\n') {
newlines++;
}
}

关于c - 如何计算文件中的换行符,但不计算只是换行符的行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43622633/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com