我试图通过系统调用获取 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内容加上错误的数据
最佳答案
根据 the read manual :
Upon successful completion, read() [XSI] [Option Start] and pread() [Option End] shall return a non-negative integer indicating the number of bytes actually read.
...您需要使用返回值来确定实际读取了多少字节(您可能不应该在此处的 buf
之前使用&符号)。
例如。 ssize_t how_many_bytes = read(filedesc, buf, BUF_SIZE);
puts
不允许您指定 how_many_bytes
,所以也许您最好使用 fwrite
。
例如。 fwrite(buf, 1, how_many_bytes, stdout);
同样,the scanf manual告诉你如何使用scanf的返回值:
Upon successful completion, these functions shall return the number of successfully matched and assigned input items; this number can be zero in the event of an early matching failure. If the input ends before the first matching failure or conversion, EOF shall be returned. If a read error occurs, the error indicator for the stream is set, EOF shall be returned, [CX] [Option Start] and errno shall be set to indicate the error. [Option End]
例如。 if (scanf("%d", &line) != 1) { 退出(0); }
关于c - 系统调用 open(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29338014/