linux 下一切皆文件 文件读写
文件的打开open函数
涉及头文件:
ubuntu 头文件所在目录:/usr/include/x86_64-linux-gnu/sys
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
具体函数:
L
参数解释:
功能:给文件出昂见一个新的文件描述符,
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 <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(int argc, char*argv[])
{
int fd = 0;
fd=open("./open_1.c",O_RDONLY);
printf("fd = %d \r\n", fd);
return 0 ;
}
输出结果:
fd = 3
读文件
这里只有读取的权限,尝试这读取下这个文件的内容并输出至屏幕;
这里就要用到 read 函数:
man 2 read 查看具体解释
#include <unistd.h>
ssize_t read(int fd, void *buf, size_t count);
功能: 从文件描述符 fd中读取 count个字节 放入buf中;
返回值: count =0 返回0
count 不为零, 文件不为空时,返回文件当前所在位置;
失败,返回-1;
读取结果:
buffer= #include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
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 < 0)
return -1;
else
return read_num;
fprintf(stdout,"buffer= %s read_num = %d ",buffer, read_num);
}
read_num = 520
好巧不巧刚好读取了520个字节哈哈
这里需要注意的是:
buffer申请的空间大小必须大于等于 count ,不然会报总线错误;
写文件
man 2 write
*#include <unistd.h>
ssize_t write(int fd, const void buf, size_t count);
参数:
fd:需要写的文件描述符;
buf:将buf中的内容写入 fd中
count: 一次写入的字节数
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
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 < 0)
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 <= 0 )
return -1;
else
return write_num;
}
想这么干嘛,你考研我学习一起努力小丹妮,一起加油
好了,先到这里,出去办点事娄回来继续;