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

时间:2019-10-22 05:17:57

标签: 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);
        }
    }
}

我如何做到这一点,使其仅将每行中的前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

2 个答案:

答案 0 :(得分:1)

最大strlen将为74。

"columns":[
        {"data":"name"},
        {"data":"tbl.Position"}, //tbl is join table alias.
        {"data":"office"},
        {"data":"age"},
        {"data":"start_date"},
        {"data":"salary"},
    ],

答案 1 :(得分:1)

类似这样的东西:

User u1 = new User("U1");  
  print(u1.name);  
> null

将其放在您的else块之后。

这是一个完整的版本,可以正确修复打印输出:

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

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'))fgets的返回值。