每次调用函数时,请读取文件的下一行

时间:2014-10-08 22:24:24

标签: c file-io

我有一个文本文件,每行都有数字。我想在C中编写一个函数来读取文件,并在每次调用函数时返回文件中的下一个数字。

例如,如果我有这些数字:

100 
200 
300 
400

和一个名为get_number()的函数,如果我调用get_number()它将返回100,如果我再次调用它,它将返回200,等等。

这是我到目前为止所写的内容,但每次调用该函数时,它总是返回到文本文件中的第一个数字。

int * get_number()
{

    FILE* file = fopen("random_numbers.txt", "r");
    char line[256];

    if (file==NULL) 
    {
        perror ("Error reading file");
    }
    else
    {
        fgets(line, sizeof(line), file);
        printf("%s", line);
    }

    return 0;
}

4 个答案:

答案 0 :(得分:0)

避免重复打开文件是个好主意。每次调用该函数时,不要打开文件,而是打开一次,然后在每次调用时将文件指针传递给函数。

int * get_number(FILE *file)
{
    char line[256];

    fgets(line, sizeof(line), file);
    printf("%s", line);

    return 0;
}

int main()
{
    FILE *file = fopen("random_numbers.txt", "r");

    if (file == NULL) 
    {
        perror("Error opening file");
        return 1;
    }

    while (!feof(file))
    {
        get_number(file);
    }

    fclose(file);
}

答案 1 :(得分:0)

  1. 在调用函数中打开文件。

  2. FILE*传递给get_number

  3. int返回get_number,而不是int*

  4. 这是经过修改的get_number

    int get_number(FILE* file)
    {
        // This is the core functionality.
        // You should add error handling code
    
        int number;
        int n = fscanf(file, "%d", &number);
        if ( n != 1 )
        {
           // Add error handling code.
        }
    
        return number;
    }
    

答案 2 :(得分:0)

这是一个完全相同的版本:

 int * get_number(long* pos)
{

    FILE* file = fopen("random_numbers.txt", "r");
    char line[256];

    if (file==NULL) 
    {
        perror ("Error reading file");
    }
    else
    {
        fseek(file , *pos , SEEK_CUR);
        fgets(line, sizeof(line), file);
        printf("%s", line);
    }
    *pos = ftell(file);
    return 0;
}

你从main这样称呼它

long pos = 0;
get_number(&pos);

或者更好的是使用静态变量

 int * get_number()
{
    static long pos = 0;
    FILE* file = fopen("random_numbers.txt", "r");
    char line[256];

    if (file==NULL) 
    {
        perror ("Error reading file");
    }
    else
    {
        fseek(file , pos , SEEK_CUR);
        fgets(line, sizeof(line), file);
        printf("%s", line);
    }
    pos = ftell(file);

    return 0;
}

答案 3 :(得分:0)

这是正常的,因为每次调用get_number()时都会打开文件; (这更糟糕,因为没有调用fclose。 你想要的可能是在get_number();给出一个文件描述符;这样:

void get_number(FILE*  file)
{

    char line[256];

    if (file==NULL) 
        perror ("Bad descriptor given");
    else
    {
        if (fgets(line, sizeof(line), file) == NULL)
             perror("Fgets failed"); 
        else
             printf("%s", line);
    }
}

除了你的职能之外,你想要的是做以下事情:

FILE * file = fopen("random_numbers.txt", "r");
get_number(file); // 100
get_number(file); // 200
fclose(file);

我让你的功能无效,因为这里的回归毫无意义。你可以改变它并使用atoi和返回功能。