C - 无法读取其中没有尾随新行的文件

时间:2016-11-22 10:04:39

标签: c newline

我正在研究C中的一个程序,它必须从文件描述符中读取一行。 如果有错误,它必须返回1,0或-1,但是使用指针的地址从main读取行。 当我想从我创建的文件中读取时,程序无法输出任何内容: echo -n" test test" > filetest1(-n不输出尾部换行符)

我使用一个数组来存储新行,直到找到\ n然后我为指针分配内存并将该行存储在其中。 该程序复制"测试测试"在指针中,但在编译时它不会输出任何内容。我不明白为什么。

  • j =返回1,0或-1。
  • buf =我存储一行的数组,直到找到\ n
  • str =存储我最初放入buf的行

我不被允许:

  • 更改get_next_line原型
  • 使用realloc,仅使用malloc
  • 使用任何其他函数从文件中读取 除了打开和阅读之外的描述符。

       #include <fcntl.h>
       #include <stdio.h>
    
       static char     *ft_read_line(int fd, char *buffer, int *j)
       {
               char    c;
               int     i;
               char    *str;
    
    
              str = NULL;
              i = 0;
    
              while ((*j = read(fd, &c, 1)) != 0)
              {
                      if (c == '\n')
                              break;
                      buffer[i++] = c;
              }
    
              if (str != NULL)
                      free(str);
    
              if (!(str = (char *)malloc(sizeof(str) * (i + 1))))
                      return (NULL);
    
              strcpy(str, buffer);
              bzero((char*)buffer, 10000000);
    
              return (str);
      }
    
      int     get_next_line(int const fd, char **line)
      {
              static char     buf[10000000];
              int     j;
    
              j = 0;
              *line = ft_read_line(fd, buf, &j);
    
              if (j < 0)
                      return (-1);
    
              return (j);
      }
    
      int     main(void)
      {
              int     fd;
              char    *line;
    
              fd = open("filetest1", O_RDONLY);
    
              while (get_next_line(fd, &line) >0)
              {
                      printf("%s\n", line);
              }
    
              close(fd);
              return (0);
      }
    

0 个答案:

没有答案