沉默的牧羊者 2017-04-08 15:15 采纳率: 75%
浏览 2322
已采纳

在Linux下通过read读文件出现的问题

#include
#include
#include
#include
#include
#include
#include
#include

#define infile "temp.dat"
#define outfile "outfile.dat"
#define length 20

void translation()
{
int creatf;
int infd, outfd;
char buf[50];

if ((creatf = open(infile, O_WRONLY | O_TRUNC | O_CREAT, 10700)) == -1)
{
    printf("ERROR, OPEN READ FILE FAILED: \n", sys_errlist[errno]);
    exit(255);
}
else
{
    printf("Create Successful\n");
}

strcpy(buf, "Hello");
if (write(creatf, buf, strlen(buf)) != strlen(buf))

{
    printf("ERROR, WRITE FILE FAILED: \n", sys_errlist[errno]);
    exit(255);
}
else
{
    printf("Write Successful\n");
}


close(creatf);

if (infd = open(infile, O_RDONLY)==-1)
{
    printf("ERROR, OPEN READ FILE FAILED: \n", sys_errlist[errno]);
    exit(255);
}
else
{
    printf("INFILE Open Success\n");
}

if (outfd = open(outfile, O_WRONLY | O_TRUNC | O_CREAT, 10700)==-1)
{
    printf("ERROR, OPEN WRITE FILE FAILED: \n", sys_errlist[errno]);
    exit(255);
}
else
{
    printf("OUTFILE Open Success\n");
}

int count;

while((count = read(infd, buf, sizeof(buf))) > 0)         //在这一行就出现程序就停下来了
{
    if (write(outfd, buf, count) != count)
    {
        printf("ERROR, WRITE FILE FAILED: \n", sys_errlist[errno]);
        exit(255);
    }
    else
    {
        printf("%s", buf);
    } 
}
close(infd);
close(outfd);

}

void main()
{
translation();
}

在读文件时,程序就停止了,我按回车后才继续显示下一步,但是和预想中的不一样!

图片说明
上图表示在此处停住了

图片说明

上图表示停住后,按下回车键时,断断续续的出现的东西(文件里面只写了"Hello")

我想问一下问题到底出在了什么地方??

  • 写回答

7条回答 默认 最新

  • 战在春秋 2017-04-08 22:01
    关注
     if (infd = open(infile, O_RDONLY)==-1)
    

    应为

     if ( (infd = open(infile, O_RDONLY) ) == -1)
    
     if (outfd = open(outfile, O_WRONLY | O_TRUNC | O_CREAT, 10700)==-1)
    

    应为:

     if ( (outfd = open(outfile, O_WRONLY | O_TRUNC | O_CREAT, 10700) ) == -1)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(6条)

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题