一.重新定位光标:
#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=“cao kuangyuan hen shuai!”;
fd = open("./file1",O_RDWR);
if(fd == -1){
printf(“open file1 failed\n”);
fd = open("./file1",O_RDWR|O_CREAT,0600);
if(fd>0){
printf("creat file1 success!\n");
}
}
printf("open success : fd = %d\n",fd);
//ssize_t write(int fd, const void *buf, size_t count);
int n_write = write(fd,buf,strlen(buf));
if(n_write!=-1){
printf("write %d byte to file1\n",n_write);
}
//close(fd);
//fd = open("./file1",O_RDWR);
//off_t lseek(int fd, off_t offset, int whence);
lseek(fd,0,SEEK_SET);
//lseek(fd,-21,SEEK_CUR);
//ssize_t read(int fd, void *buf, size_t count);
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;
}
二.计算文件大小(字节数)
#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=“cao kuangyuan hen shuai!”;
fd = open("./file1",O_RDWR);
int filesize = lseek(fd,0,SEEK_END);
printf(“file size is: %d\n”,filesize);
close(fd);
return 0;
}