一.文件打开与创建
int open(const char *pathname,int flags);
Pathname:要打开的文件名(含路径,缺省为当前路径)
Flags:O_RDONLY只读打开 O_WRONLY只写打开 O_RDWR可读可写打开
编写代码
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
int main()
{
int fd;
fd=open("./file",O_RDWR);
printf("fd=%d\n",fd);
return 0;
}
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
int main()
{
int fd;
fd=open("./file",O_RDWR);
if(fd=-1)
{
printf("open file1 failed\n");
fd =open("./filed",O_RDWR|O_CREAT,0600);
if(fd>0){
printf("creat file1 success!\n");
}
}
return 0;
}
~
ls -l 列出所有清单
可读 r 可写w 执行x 可读可写rw
二.文件写入
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
int main()
{
int fd;
char *buf ="zhongguo jiayou!"
fd=open("./file",O_RDWR);
if(fd=-1)
{
printf("open file1 failed\n");
fd =open("./filed",O_RDWR|O_CREAT,0600);
if(fd>0){
printf("creat file1 success!\n");
}
}
printf("open susceess:fd=%d\n",fd)
write(fd,buf,sizeof(buf));
close(fd);
return 0;
}
读取文件
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int main()
{
int fd;
char *buf ="zhongguo jiayou!";
fd=open("./file",O_RDWR);
if(fd=-1)
{
printf("open file1 failed\n");
fd =open("./filed",O_RDWR|O_CREAT,0600);
if(fd>0){
printf("creat file1 success!\n");
}
}
printf("open susceess:fd=%d\n",fd);
int n_write=write(fd,buf,sizeof(buf));
if(n_write!=-1)
{
printf("write %d byte to file\n",n_write);
}
char *readBuf;
readBuf=(char *)malloc(sizeof(char)*n_write+1);
int n_read=read(fd,readBuf,n_write);
printf("read %d,context:%s\n",n_read,readBuf);
close(fd);
return 0;
}
在Linux中要操作一个文件,一般是先open打开一个文件,得到文件描述符,然后对文件进行读写操作(其他操作),最后是close关闭文件即可。