简体   繁体   English

C - 逐行读取文件

[英]C - Read file line by line

The code is running well, it's just that I feel there are still many mistakes and give me a little direction to improve in the future.代码运行的很好,只是感觉还是有很多错误,给我一个以后改进的小方向。 I want to learn how to maintain the code properly.我想学习如何正确维护代码。

fix the code as it should!修复代码,因为它应该!

Data.txt数据.txt

[1] Line numbers 1.
[2] Line numbers 2.
[3] Line numbers 3.
[4] Line numbers 4.
[5] Line numbers 5.
[6] Line numbers 6.

My code:我的代码:

#include <stdio.h>
#include <stdlib.h>

int getLengthFile(char *namafile)
{
    FILE *fptr;
    int n =0;
    fptr = fopen(namafile, "r");
    if(fptr != NULL){
        char c;
        while((c = getc(fptr)) != EOF) {
            ++n;
        }
        fclose(fptr);
    }
    return n;
}

int main(){
    FILE *fptr;
    int i;
    fptr = fopen("Data.txt","r");
    if(fptr != NULL){
        printf("Succes reads file!\n");
        if(getLengthFile("Data.txt")>0){
            char strLine[225];
            while(fgets(strLine,225,fptr) != NULL){
                printf("%s",strLine);
            }
        }else{
            printf("File is empty!\n");
        }
        fclose(fptr);
    }else{
        printf("Error reads file!\n");
    }

    return 0;
}

Here is a more or less fixed version of the code presented in the first edition of the question, where the getLengthFile() function was not present.这是问题第一版中提供的代码或多或少的固定版本,其中不存在getLengthFile()函数。 In my opinion, that function does not provide useful functionality.在我看来,该功能没有提供有用的功能。 If you must report that the file contained no data, you could do so by counting the number of times fgets() returns any data — if it returns any data, the file was not empty.如果您必须报告该文件不包含任何数据,您可以通过计算fgets()返回任何数据的次数来报告 — 如果它返回任何数据,则该文件不为空。

#include <stdio.h>

int main(void)
{
    const char filename[] = "Data.txt";
    FILE *fptr = fopen(filename, "r");
    if (fptr == NULL)
    {
        fprintf(stderr, "Error opening file %s for reading!\n", filename);
        return 1;
    }
    printf("Success opening file %s for reading\n", filename);
    char strLine[225];
    while (fgets(strLine, sizeof(strLine), fptr) != NULL)
        printf("%s", strLine);
    fclose(fptr);

    return 0;
}

When there is no file Data.txt , example output is:当没有文件Data.txt ,示例输出为:

Error opening file Data.txt for reading!

When there's a file containing one short line of data, example output is:当文件中包含一行短数据时,示例输出为:

Success opening file Data.txt for reading
data from the file Data.txt

I also tested it on a file with longer lines, including lines with as many as 380 characters, and the output from the program was the same as the input except for the line saying 'Success opening file Data.txt for reading'.我还在一个具有更长行的文件上对其进行了测试,包括多达 380 个字符的行,程序的输出与输入相同,除了“成功打开文件 Data.txt 进行阅读”这一行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM