鉴于C中的文件名,如何仅读取75个字符的每一行?

问题描述 投票:0回答:2

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

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);
        }
    }
}

如何使它仅将每行的前75个字符保​​存到变量line中?

上面的代码提供以下输出:

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
c fgets
2个回答
1
投票

最大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;
}

1
投票

类似这样的东西:

// If we read an incomplete line
if(strlen(line) == 74 && line[73] != '\n') {
    // Read until next newline
    int ch; // Yes, should be int and not char
    while((ch = fgetc(fp)) != EOF) {
        if(ch == '\n') 
            break;
    }
}

将其放在您的else块之后。

这里是正确修复打印输出的完整版本:

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

        if(strlen(line) == 74 && line[73] != '\n') {
            // ... unless the string is too long
            printf("\n");
            int ch; 
            while((ch = fgetc(fp)) != EOF) {
                if(ch == '\n') 
                    break;
            }
        }
    }
}

if(strlen(line) == 74 && line[73] != '\n')可以用if(strchr(line, '\n'))代替。

当然,在出现错误的情况下,您应该检查fgetsfopen的返回值。

© www.soinside.com 2019 - 2024. All rights reserved.