在将数据读入缓冲区时读取额外的字符
Reading extra characters while reading data into buffer
我正在编写一个程序,在通过文件读取数据后通过管道发送数据。有时代码工作正常,但有时会读取一些额外的字符。但是代码工作得很好是 BUF_SIZE
是 1。我猜我正在读取一些额外的或垃圾数据,但我不知道在哪里。
额外字符如:
ÀêÒî
#include <iostream>
#include <fstream>
#include <sys/wait.h>
#include <unistd.h>
using namespace std;
#define BUF_SIZE 512
int main(){
int fd[2];
char buf[BUF_SIZE];
pipe(fd);
switch(fork()){
default:{
close(fd[1]);
fstream o;
o.open("out.txt",fstream::trunc|fstream::out);
int numread;
while(1){
numread=read(fd[0],buf,BUF_SIZE);
if(numread<0) continue;
if(numread==0) break;
o<<buf;
}
o.close();
close(fd[0]);
wait(NULL);
break;
}
case 0:
close(fd[0]);
ifstream inp("in.txt");
char buf2[BUF_SIZE];
while(inp){
inp.read(buf2,BUF_SIZE);
if(inp.gcount()!=0)
write(fd[1],buf2,inp.gcount());
}
inp.close();
close(fd[1]);
}
}
改变
char buf[BUF_SIZE];
进入
char buf[BUF_SIZE+1];
并插入
buf[numread]=0;
之前
o<<buf;
否则buf在read
接收到的数据后面包含垃圾数据,并且o << buf将复制该垃圾数据直到找到'[=15=]'
我正在编写一个程序,在通过文件读取数据后通过管道发送数据。有时代码工作正常,但有时会读取一些额外的字符。但是代码工作得很好是 BUF_SIZE
是 1。我猜我正在读取一些额外的或垃圾数据,但我不知道在哪里。
额外字符如:
ÀêÒî
#include <iostream>
#include <fstream>
#include <sys/wait.h>
#include <unistd.h>
using namespace std;
#define BUF_SIZE 512
int main(){
int fd[2];
char buf[BUF_SIZE];
pipe(fd);
switch(fork()){
default:{
close(fd[1]);
fstream o;
o.open("out.txt",fstream::trunc|fstream::out);
int numread;
while(1){
numread=read(fd[0],buf,BUF_SIZE);
if(numread<0) continue;
if(numread==0) break;
o<<buf;
}
o.close();
close(fd[0]);
wait(NULL);
break;
}
case 0:
close(fd[0]);
ifstream inp("in.txt");
char buf2[BUF_SIZE];
while(inp){
inp.read(buf2,BUF_SIZE);
if(inp.gcount()!=0)
write(fd[1],buf2,inp.gcount());
}
inp.close();
close(fd[1]);
}
}
改变
char buf[BUF_SIZE];
进入
char buf[BUF_SIZE+1];
并插入
buf[numread]=0;
之前
o<<buf;
否则buf在read
接收到的数据后面包含垃圾数据,并且o << buf将复制该垃圾数据直到找到'[=15=]'