Linux系统打开文件的正确方法是什么,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。
文件的打开open函数 涉及头文件: ubuntu 头文件所在目录:/usr/include/x86_64-linux-gnu/sys #include
参数解释:
功能:给文件出昂见一个新的文件描述符,
pathname:指定一个文件路径
flags: 读取文件的模式O_RDONLY, O_WRONLY, or O_RDWR
mode:读取文件的权限指定
S_IRWXU == 00700 用户有 读写执行权限 S_IRUSR 00400 user has read permission S_IWUSR 00200 user has write permission S_IXUSR 00100 user has execute permission S_IRWXG 00070
group has read, write and execute permission S_IRGRP 00040
group has read permission S_IWGRP 00020
group has write permission S_IXGRP 00010
group has execute permission S_IRWXO 00007 others have read, write and execute permission S_IROTH 00004 others have read permission S_IWOTH 00002 others have write permission S_IXOTH 00001 others have execute permission
返回值: successfully 返回一个文件描述符非负整数,
#include #include #include #include int main(int argc, char*argv[]) { int fd = 0; fd=open("./open_1.c",O_RDONLY); printf("fd = %d \r\n", fd); return 0 ; } 1234567891011121314 输出结果: fd = 3 12
读文件
这里只有读取的权限,尝试这读取下这个文件的内容并输出至屏幕; 这里就要用到 read 函数: man 2 read 查看具体解释 #include
读取结果: buffer= #include #include #include #include #include int display_file(int,int); int main(int argc, char*argv[]) { int fd = 0; fd=open("./open_1.c",O_RDONLY); //printf("fd = %d \r\n", fd); display_file(fd, 1024); return 0 ; } int display_file(int fd, int count) { char buffer[100]; memset(buffer, 0, sizeof(buffer)); if(0 > fd || 0 >= count) return -1; int read_num = read(fd,buffer,count); if (read_num return -1; else return read_num; fprintf(stdout,"buffer= %s read_num = %d ",buffer, read_num); } read_num = 520 好巧不巧刚好读取了520个字节哈哈 123456789101112131415161718192021222324252627282930313233
这里需要注意的是: buffer申请的空间大小必须大于等于 count ,不然会报总线错误;
写文件
man 2 write #include
#include #include #include #include #include int display_file(int,char *, int); int main(int argc, char*argv[]) { int fd = 0; int fdw = 0; char buffer[1024]; memset(buffer, 0, sizeof(buffer)); fd=open("./open",O_RDONLY); fdw = open("./open_2", O_RDWR|O_CREAT, S_IWUSR|S_IRUSR|S_IROTH); //printf("fd = %d \r\n", fd); display_file(fd, buffer,1024); write_to_file(fdw,buffer,1024); return 0 ; } int display_file(int fd, char * buf, int count) { char * buffer = NULL; buffer = buf; if(0 > fd || 0 >= count || NULL == buf) return -1; int read_num = read(fd,buffer,count); if (read_num return -1; else return read_num; fprintf(stdout,"buffer= %s read_num = %d \r\n",buffer, read_num); } int write_to_file(int fd,char* buff, int count) { int write_num = write(fd, buff,count); if (write_num return -1; else return write_num; }
关于Linux系统打开文件的正确方法是什么问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注编程网行业资讯频道了解更多相关知识。