使用Run-Time c 函数open的注意事项

来源:互联网 发布:网络电视播放器排行 编辑:程序博客网 时间:2024/05/16 10:21

1.c语言,变量只能在函数开头部分声明,不能在除此之外的任意地方声明。

2.初学者易犯的错误。

int fd;

char file_path[1024];

.....

if ( fd  =  open(file_path,O_RDONLY ) < 0) 

{

    goto err;

}

.....

:err

注:无论file_paht为何值,fd = 0!!!!!!!!, 因为 符号 "<"的优先级大于 符号“=",open(file_path,O_RDONLY)<0的表达式值始终为假

正确写法:if ( (fd  =  open(file_path,O_RDONLY ) ) < 0)

3.

int n_f;

struct stat st;

char buf[1024];

fd  = open(file_path, O_RDONLY|O_BINARY);

fstat(fd,&st);

n_f = read(file_paht,buf,st.st_size);

注:只有在open函数中添加O_BINARY选项,read函数才能读出文件的正确大小,否则n_f值小于st.st_size





0 0
原创粉丝点击