【发布时间】:2015-06-02 23:37:59
【问题描述】:
我试图通过系统调用获取 txt 文件的内容,但是当我的程序再次调用 open() 函数时,缓冲区得到了奇怪的数据。
void delFunction(){
int BUF_SIZE=8192;
int line=0,cont=0,x=0,y=0;
char buf[BUF_SIZE];
char buf2[BUF_SIZE];
char buf3[BUF_SIZE];
fflush(stdin);
int filedesc = open("testfile.txt", O_RDONLY);
read(filedesc, &buf, BUF_SIZE);
close(filedesc);
printf("BUFFER: \n");
puts(buf);
printf("Choose the line you want delete\n");
scanf("%d",&line);
for(x=0;x<strlen(buf);x++){
if(line==cont){
}else{
buf2[y]=buf[x];
y++;`
}
if(buf[x]=='\n'){
puts(buf2);
cont++;
}
}
int filedesc2 = open("testfile.txt", O_WRONLY | O_TRUNC);
write(filedesc2,buf2, strlen(buf2));
close(filedesc2);
buf2[0]='\0';
}
第一次程序运行良好,但第二次缓冲区获取的 .txt 内容加上错误的数据
【问题讨论】:
-
read()不会为您终止缓冲区。您不会检查 任何 系统调用的返回值。
标签: c system-calls