【问题标题】:Given a filename in C how to read each line for only 75 characters?给定 C 中的文件名,如何仅读取 75 个字符的每一行?
【发布时间】:2019-10-22 05:17:57
【问题描述】:

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

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

【问题讨论】:

  • 请注意,从技术上讲,不可能只读取每行的前 75 个字符。您仍然需要阅读整行才能找到行终止符。

标签: c fgets


【解决方案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;
}

【讨论】:

  • 当你说“最大 strlen 将是 74”时,是否意味着我需要声明 char line[74]?
  • fgets 通常 get 传递传递的字符数组的大小,其中包括终止 \0。因此 75 允许 strlen 少 1。
  • 那么我需要为 char line[?] 放什么?
  • char line[75+1], fgets(... 75+1 ...) 用于长度为 75 的行
  • 假设我需要将“line”作为参数传递,我将把语句放在哪里?会在最后一个 if 语句中吗?
【解决方案2】:

类似这样的:

// 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 的返回值。

【讨论】:

  • 我遇到了分段错误 11
  • @NeelPatel 我没有
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-04
  • 2015-03-01
  • 1970-01-01
  • 2023-03-10
  • 2015-08-27
  • 2013-05-17
  • 2016-06-16
相关资源
最近更新 更多