#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
int main()
{
int fd;
char *buf = "longhaiyang hengshuai!";
fd = open("./file1",O_RDWR);
if(fd == -1){
printf("文件打开失败!\n");
fd = open("./file1",O_RDWR|O_CREAT,0600);
if(fd >0){
printf("创建文件成功!\n");
}
}
int n_write = write(fd,buf,strlen(buf));
if(n_write != -1){
printf("write %d byte to file1!\n",n_write);
}
char *readbuf;
readbuf = (char *)malloc(sizeof(char)*n_write+1);
lseek(fd,0,SEEK_SET);
int n_read = read(fd,readbuf,n_write);
printf("read %d byte to readbuf,context:%s\n",n_read,readbuf);
close(fd);
}
/*
还可以通过SEEK_END计算文件的大小
int filesize = lseek(fd,0,SEEK_END);//会返回文件的大小
printf("file's size is:%d\n",filesize);
*/```
Linux文件编程demo5文件光标移动操作.c
Linux系统C语言文件编程
最新推荐文章于 2025-12-04 16:38:42 发布

1182

被折叠的 条评论
为什么被折叠?



