文件编程篇
一、文件的打开及创建
文件打开函数原型:
int open(const char *pathname, int flags);
int open(const char *pathname, int flags, mode_t mode);
1)pthname:要打开的文件名(含路径,缺省为当前路径)
flas:O_RDONLY 只读打开 O_WRONLY 只写打开 O_RDWR 可读可写打开
2)当我们附带了权限后,打开的文件就只能按照这种权限来操作。
以上这三个常数中应当只指定一个。下列常数是可选择的:
O_CREAT 若文件不存在则创建它。使用此选项时,需同时说明第三个参数mode,用其说明该新文件的存取许可权限。
O_EXCL 如果同时指定了O_CREAT,而文件已经存在,则出错。
O_APPEND 每次写时都加到文件尾端。
O_TRUNC 属性去打开文件时,如果这个文件中本来是有内容的,而且为只读或者只写成功打开,则将其长度截短为0。
3)Mode:一定是在flags中使用了O_CREAT标志,mode记录待创建的文件的访问权限
#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("打开文件失败!\n");
fd = open("./file",O_RDWR|O_CREAT,0600);
if(fd > 0){
printf("创建文件成功!\n");
}
}
return 0;
}
运行结果:
- 定义了一个fd来接收open函数的返回值
- open函数使用成功返回大于0的正数,失败返回-1**
二、文件写入操作
文件写入函数原型:
ssize_t write(int fd, const void *buf, size_t count);
第一个参数是文件标示符fd,将要写入到该文件中去
第二个参数是一个无类型的指针,也就是要写入的内容
第三个参数是要写入的大小
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
#include<stdio.h>
int main()
{
int fd;
char *buf = "i am handsome!";
fd = open("./file",O_RDWR);
if(fd == -1){
printf("打开文件失败!\n");
fd = open("./file",O_RDWR|O_CREAT,0600);
if(fd > 0){
printf("创建文件成功!\n");
}
}
printf("fd的返回值是:%d\n",fd);
write(fd,buf,strlen(buf));
close(fd);
return 0;
}
- 很显然,我们成功的创建了file文件,并且把定义的buf字符串指针的内容写入到了file文件当中去了。
三、文件读取操作和文件光标移动操作
1.文件读取操作
文件读取函数原型:
ssize_t read(int fd, void *buf, size_t count);
第一个参数是需要读取的fd指向的文件
第二个参数是获取到读到数据的内容
第三个参数是需要读取数据的大小
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
#include<stdio.h>
#include<stdlib.h>
int main()
{
int fd;
char *buf = "i am handsome!";
fd = open("./file",O_RDWR);
if(fd == -1){
printf("打开文件失败!\n");
fd = open("./