c - 系统调用 open()

标签 c system-calls

我试图通过系统调用获取 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); }

Don't flush stdin ...

关于c - 系统调用 open(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29338014/

相关文章:

c# - 从 Visual Studio 中的 C# 代码传递到 C 代码

c - 使用#define 定义结构对象

C 并发程序(连载)

c++ - Qt 在系统调用时崩溃?

windows - 获取固定驱动器列表

linux - 尝试理解 sys_socketcall 参数

python - 在 python 中使用 swig 包装的 typedef 结构和枚举来转换字符串/缓冲区数据

c - 输入 esc 字符存储十进制值 10,而它应该显示值 27

c - ntohl 在 sin_port 上使用并得到负数

c - open() 如何有两个定义,如手册页所示?