#include <sys/types.h> #include <sys/stat.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <errno.h> #include <unistd.h> #include <fcntl.h> #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”)
本人想问一下问题到底出在了什么地方?
解决方案
20
问题出在第45行和第55行。
第45行应该是:
第45行应该是:
if ((infd = open(infile, O_RDONLY))==-1)
第55行应该是:
if ((outfd = open(outfile, O_WRONLY | O_TRUNC | O_CREAT, 10700))==-1)
你的程序infd和outfd都是0,那么read函数会从stdin读取输入,你输入enter,那么read把换行符放入buf的第一个位置,从而替换了第一个字符H,所以打印出来的是一个换行符加上以前buf里面的index从1开始的值,直到\0。所以你看到ello。