为什么我的程序自己读取程序而不是文本文件?我要做的是读取一个文本文件,找出最长的文本行,然后输出该行以及它包含的字符数。
#include <stdio.h>
#define MAXLINE 1000 /* maximum input line size */
int getline1(char line[], int maxline);
void copy1(char to[], char from[]);
/* print longest input line */
int main(void)
{
int len; /* current line length */
int max; /* maximum length seen so far */
char line[MAXLINE]; /* current input line */
char longest[MAXLINE]; /* longest line saved here */
max = 0;
FILE *ptr_file;
ptr_file =fopen("textfile.txt","r");
if (!ptr_file)
return 1;
while (fgets(line,1000, ptr_file)!=NULL)
//printf("%s",line);
//fclose(ptr_file);
//return 0;
while((len = getline1(line, MAXLINE)) > 0)
{
printf("%d: %s", len, line);
if(len > max)
{
max = len;
copy1(longest, line);
}
}
if(max > 0)
{
printf("Longest is %d characters:\n%s", max, longest);
}
printf("\n");
return 0;
} //end main
/* getline: read a line into s, return length */
int getline1(char s[], int lim)
{
int c, i, j;
for(i = 0, j = 0; (c = getchar())!=EOF && c != '\n'; ++i)
{
if(i < lim - 1)
{
s[j++] = c;
}
}
if(c == '\n')
{
if(i <= lim - 1)
{
s[j++] = c;
}
++i;
}
s[j] = '\0';
return i;
}
/* copy: copy 'from' into 'to'; assume 'to' is big enough */
void copy1(char to[], char from[])
{
int i;
i = 0;
while((to[i] = from[i]) != '\0')
{
++i;
}
}
答案 0 :(得分:1)
你的main中的while循环应该是这样的(不需要内部getline1()
getchar()
从stdin读取的内部循环):
while (fgets(line, 1000, ptr_file)!=NULL) {
len = strlen(line);
if (len > max) {
max = len;
strncpy(longest, line, 1000);
}