Linux的文件系统操作调用涉及创建、打开、读写和关闭文件。
int creat(const char *filename,mode_t mode);
int open(const char *pathname, int flags); 常用的有 O_RDONLY; O_WRPNLY; O_RDWR; O_CREAT
int open(const char *pathname,int flags,mode_t mode);
int read(int fd,const void *buf,size_t length);
int write(int fd,const void *buf,size_t length);
定位:对于随机文件,可以随机指定位置读写,使用如下函数进行定位。
int lseek(int fd, offset_t offset, int whence); 返回值为文件指针相对于文件头的位置。
int close(int fd);
代码例程:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#define LENGTH 100
main()
{
int fd,len;
fd = open ("hello.txt", O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
if (fd) {
write (fd,"Hello World", strlen("hello world"));
close(fd);
}
fd = open("hello.txt",O_RDWR);
len = read(fd, str, LENGTH);
str[len] = '\0';
printf("%s\n", str);
close(fd);
}
常用C库文件系统操作:
FILE *fopen(const char *path,const char *mode);
int fgetc(FILE stream);
int fput(int c,FILE *stream);
size_t fread(void *ptr,size_t size,size_t n,FILE *stream);
size_t fwrite(const void *ptr,size_t size,size_t n,FILE *stream);
int fclose(FILE *stream);
例程:
#include <stdio.h>
#define LENGTH 100
main()
{
FILE *fd;
char str[LENGTH];
fd = fopen("hello.txt","w+");
if (fd) {
fputs("hello world",fd);
fclose(fd);
}
fd = fopen("hello.txt","r");
fgets(str,LENGTH,fd);
printf("%s\n",str);
fclose(fd);
}