gpt4 book ai didi

c - 读取输出文件有多少行

转载 作者:行者123 更新时间:2023-11-30 20:14:37 25 4
gpt4 key购买 nike

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

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;
}

关于c - 读取输出文件有多少行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25708974/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com