c - 在 C 中给定一个文件名,如何读取每行只有 75 个字符?

标签 c fgets

假设我有一个包含以下内容的文件:

This line contains more than 75 characters due to the fact that I have made it that long. 
Testingstring1
testingstring2

这是我的代码:

void checkLine( char const fileName[]){
    FILE *fp = fopen(fileName,"r");
    char line[75];
    while (1) {
        fgets(line,75,fp);
        if (feof(fp)){
            break;
        } else {
            printf("%s\n", line);
        }
    }
}

如何让它只保存变量 line 中每行的前 75 个字符?

上面的代码给出了以下输出:

This line contains more than 75 characters due to the fact that I have mad
e it that long.

Testingstring1

testingstring2

预期的输出应该是这样的:

This line contains more than 75 characters due to the fact that I have mad
Teststring1
Teststring2

最佳答案

最大 strlen 将为 74。

bool prior_line_ended = true;
while (1) {
    fgets(line, 75, fp);
    if (feof(fp)){
        break;
    }

    // Remove any line end:

    char* pos = strchr(line, '\n');
    //char* pos = strchr(line, '\r');
    //if (pos == NULL) {
    //    pos = strchr(line, '\n');
    //}
    bool line_ended = pos != NULL;
    if (line_ended) {
        *pos = '\0';
    }

    // Output when starting fresh line:

    if (prior_line_ended) {
        printf("%s\n", line);
    }
    prior_line_ended = line_ended;
}

关于c - 在 C 中给定一个文件名,如何读取每行只有 75 个字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58497508/

相关文章:

c - 当缓冲区太大时 fgets() 会阻塞

c - 从任何数据函数读取打印行

c - 使用单独的 fget(嵌套 fget)抓取下一行

c++ - 我如何故意触发 fgets() 中的错误?

c - 操作系统 : Why is GetProcessInformation() causing a segfault?

c - 接收和打印

c++ - 从 C++ 调用 Python

c - sscanf 复制的数据超过可变大小

c - 传入C的二维数组

c - 在 C 中使用 fgets 找到特定标记后读取文件的部分内容