Учитывая имя файла в C, как прочитать каждую строку только для 75 символов? - PullRequest
0 голосов
/ 22 октября 2019

Предположим, у меня есть файл, который содержит содержимое ниже:

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 ]

1 голос
/ 22 октября 2019

Примерно так:

// 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')), если вы предпочитаете.

И, конечно,, вы должны проверить возвращаемое значение для fgets и fopen в случае ошибки.

1 голос
/ 22 октября 2019

Максимальная строка будет 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;
}
...