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

给定一个C文件名,如何读取每行仅75个字符?,c,fgets,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]; whil

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

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个字符

上述代码提供以下输出:

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;
}
大概是这样的:

// 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(strhr(line,'\n'))
,如果您愿意的话


当然,如果出现错误,您应该检查
fgets
fopen
的返回值。

请注意,从技术上讲,不可能只读取每行的前75个字符。您仍然需要阅读整行以找到行终止符。当您说“最大strlen将为74”时,这是否意味着我需要声明char行[74]?一般来说,get传递传递的字符数组的大小,其中包括终止的
\0
。因此,75允许strlen小于1。那么,对于字符行[?]?
字符行[75+1],对于长度为75的行,我需要放置什么,fgets(…75+1…
假设我需要将“line”作为参数传递,我将把语句放在哪里?它会出现在最后一个if语句中吗?我有一个分段错误11@NeelPatel我没有