Linux文件操作实例
1.打开/创建文件
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
extern int errno;
int main()
{
int fd;
fd=open("./test.dat",O_CREAT|O_RDWR,S_IRWXU); //可读可写,允许当前用户读写操作,若文件不存在则创建,存在则直接打开
if(-1==fd)
{
switch (errno)
{
case EEXIST:
printf("File exist!\n");
break;
default:
printf("open file fail!\n");
break;
}
return 0;
}
printf("文件已创建/打开\n");
close(fd);
return 0
}
2.读写文件
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
extern int errno;
int main()
{
int fd;
fd=open("./test.dat",O_CREAT|O_RDWR,S_IRWXU); //可读可写,允许当前用户读写操作,若文件不存在则创建,存在则直接打开
if(-1==fd)
{
switch (errno)
{
case EEXIST:
printf("File exist!\n");
break;
default:
printf("open file fail!\n");
break;
}
return 0;
}
printf("文件已创建/打开\n");
char *buf="this is new world!\n";
char text[64];
write(fd,buf,strlen(buf));
lseek(fd,0,SEEK_SET); //文件指针回到文件开头位置
int num_read=(int)read(fd,text,64); //读取数据
printf("读取数据量:%d\n",num_read);
printf("读取完成!\n");
puts(text); //输出数据
close(fd);
return 0;
}
3.覆盖内容
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
extern int errno;
int main()
{
int fd,file_mode,num_read;
char buf[64]="this is a posix file !(line1)\n",text[64];
off_t curr_pos;
fd=open("./test.dat",O_CREAT|O_RDWR,S_IRWXU); //可读可写,允许当前用户读写操作,若文件不存在则创建,存在则直接打开
if(-1==fd)
{
switch (errno)
{
case EEXIST:
printf("File exist!\n");
break;
default:
printf("open file fail!\n");
break;
}
return 0;
}
write(fd,buf,strlen(buf)); //写入数据
curr_pos=lseek(fd,0,SEEK_CUR); //获取当前文件指针位置
printf("File Point at:%d\n",(int)curr_pos);
lseek(fd,0,SEEK_SET); //文件指针回到文件开头位置
num_read=(int)read(fd,text,64); //读取数据
printf("读取初始数据量:%d\n",num_read);
puts(text); //输出数据
lseek(fd,0,SEEK_SET); //文件指针回到文件开头位置
strcpy(buf,"File Pointer Moved!\n");
write(fd,buf,strlen(buf)); //覆盖内容
lseek(fd,0,SEEK_SET); //文件指针回到文件开头位置
num_read=(int)read(fd,text,64); //读取数据
printf("读取最终数据量:%d\n",num_read);
puts(text); //输出数据
file_mode=fcntl(fd,F_GETFL); //获取文件状态标记
if(-1!=file_mode)
{
switch(file_mode&O_ACCMODE)
{
case O_RDONLY:
printf("file mode is READ ONLY\n");
break;
case O_WRONLY:
printf("file mode is WRITE ONLY\n");
break;
case O_RDWR:
printf("file mode is READ & WRITE\n");
break;
}
}
close(fd);
return 0;
}
剩下的拓展,由你们自己去写了。
hold on and focus on the only thing.