为什么我的程序读取的是程序本身而不是我的文本文件?我要做的是读取一个文本文件并找出哪一行文本最长,然后输出该行以及它包含多少个字符。
#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;
}
}