0

为什么我的程序读取的是程序本身而不是我的文本文件?我要做的是读取一个文本文件并找出哪一行文本最长,然后输出该行以及它包含多少个字符。

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

1 回答 1

1

您 main 中的 while 循环应该看起来像(不需要内部循环,其中 insidegetline1() getchar()从 stdin 读取):

  while (fgets(line, 1000, ptr_file)!=NULL) {
    len = strlen(line);
    if (len > max) {
      max = len;
      strncpy(longest, line, 1000);
  }
于 2013-10-09T21:28:23.437 回答