这是我的问题。输出文件为七行,如下所示:

Dinda
Jane
is
so
beautiful
and
handsome.


我们被要求读取输出文件有几行。但是,两行应仅计为1。因此,此程序中的确切行数应为四(包括最后一行)。我应该如何一次读两行?这就是我到目前为止所得到的。

#include<stdio.h>
main()
{
    FILE *fp;
    char filename[25];
    char c[25][25];
    int a;

    clrscr();

    printf("Enter File Name: ");
    gets(filename);

    if(filename==NULL)
    {
        printf("\nERROR! File Doesn't Exist!");
    }
    else
    {
        fp=fopen(filename,"r");

        while(!feof(fp))
        {
            fgets(&c,sizeof(c),fp);
            printf("%s",c);
            if(strlen(c))
            {
                a++;
            }
        }

        printf("The Number of Words are: %d",a);
        fclose(fp);
        getch();
    }
}

最佳答案

像这样简单地做一下,为什么会很难(读两行):

#include<stdio.h>
#include<string.h>
main()
{
    FILE *fp;
    char filename[25];
    char buffer[256];
    int buffer_size = sizeof(buffer);
    int a=0;

    printf("Enter File Name: ");
    fgets(filename,sizeof(filename),stdin); //Always use fgets
    filename[strlen(filename)-1]='\0'; //Remove \n from the filename

    fp=fopen(filename,"r");
    if(fp==NULL) //Check if file pointer is NULL then return
    {
        printf("\nERROR! File Doesn't Exist!");
        return;
    }

    while (fgets(buffer, buffer_size, fp)) //Count number of lines in file
    {
        a++;
    }

    fclose(fp);

    //If number of lines are even then just divide by 2 else divide by 2 and add one
    if (a % 2 == 0)
        a = (a / 2);
    else
        a = (a / 2) + 1;

    printf("The Number of lines are: %d",a);
    return 0;
}

10-04 13:29