【问题标题】:System call open()系统调用 open()
【发布时间】: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


【解决方案1】:

根据the read manual

成功完成后,read() [XSI] [Option Start] 和 pread() [Option End] 应返回一个非负整数,指示实际读取的字节数。

...您需要使用返回值来确定实际读取了多少字节(您可能不应该在 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的返回值:

成功完成后,这些函数应返回成功匹配和分配的输入项的数量;如果发生早期匹配失败,此数字可以为零。如果输入在第一次匹配失败或转换之前结束,则返回 EOF。如果发生读取错误,则设置流的错误指示符,返回 EOF,设置 [CX] [Option Start] 和 errno 以指示错误。 [选项结束]

例如。 if (scanf("%d", &amp;line) != 1) { exit(0); }

Don't flush stdin...

【讨论】:

    猜你喜欢
    • 2015-01-06
    • 1970-01-01
    • 2010-10-10
    • 2012-10-21
    • 1970-01-01
    • 2013-02-15
    • 2021-09-16
    • 1970-01-01
    • 2015-04-20
    相关资源
    最近更新 更多