我正在尝试从文件逐行读取,但始终会出现打印异常。
我得到了很多印刷品,它们看起来像正方形,分为4个小正方形,其中0个。

这是我的代码:
(我只读了三行)
(如果我不写if(...)中断;它将按原样打印文件,并且不打印奇怪的符号)

while(i<3)
    {
        while(read(fdin,buff,1)>0 )
        {
            if (strcmp(buff,"\n")==0)
                break;
            strcat(ch,buff);
        }
        printf("%s\n","********");
        printf("%s\n",ch);
        memset(ch,NULL,100);
        i++;
    }


我读取的文件:(我读取路径)

/home/user/Desktop/dir1
/home/user/Desktop/dir2
/home/user/Desktop/dir3

最佳答案

由于您一次只读取一个字符(效率不高,因为每个read是系统调用),因此请尝试使用此代码,该代码不使用任何C字符串操作,而只是检查字符飞行并随着行进建立结果线。

#include <errno.h>
#include <stdio.h>
#include <stdlib.h>

char s[100], * p = s, * e = s + 100;

for (;;)
{
    if (p == e)
    {
        /* overflow */
        fprintf(stderr, "Input line too long.\n";)
        abort();
    }

    errno = 0
    n = read(fdin, p, 1);

    if (n == 0 || *p == '\n')
    {
        *p = '\0';
        printf("Line: '%s'\n", s);

        // or: fwrite(s, 1, p - s, stdout)

        if (n == 0)
        {
            /* end of file */
            break;
        }
        else
        {
            /* reset, next line */
            p = s;
        }
    }
    else if (n < 0)
    {
        printf("Error: %s\n", strerror(errno));
        abort();
    }
    else
    {
        ++p;
    }
}

关于c - 从文件逐行读取,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27583070/

10-14 15:25
查看更多