2.1 打開文件和關閉文件
#include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> |
頭文件 |
| int open(const char *pathname, int flags); |
打開一個文件 |
| int close(int fildes); |
關閉一個文件 |
1.打開文件
int open(const char *pathname, int flags);
//const char *pathname 是要打開的文件路徑
//int flag 是文件打開的標志 。 標志有 主標志 和 副標志 。
// 主標志是互斥的。三選一
// O_RDONLY 只讀方式打開
// O_RDWR 讀寫方式打開
// O_WRONLY 只寫方式打開
// 副標志可以多選
// O_APPEND 讀寫文件從文件末尾處追加
// O_TRUNC 若文件存在並可寫,則用清空的方式打開文件
// O_CREAT 若文件不存在,則創建該文件
// O_EXCL ??
// 如果用O_CREAT 方式創建不存在的文件, open則需要額外設置文件權限
int open(const char *pathname, int flags, mode_t mode);
//mode_t mode 用0755 或者其他權限寫入即可 .
//創建文件的另一個函數,用法同open
int creat(const char* pathname, mode_t mode);
2.關閉文件
// 在使用完文件后,必須正常關閉文件!!
close(int fildes);
舉個栗子:
/*
============================================================================
Name : hello.c
Author :
Version :
Copyright : Your copyright notice
Description : Hello World in C, Ansi-style
============================================================================
*/
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h> //open
#include <unistd.h> //close
int main(void)
{
int fd;
const char* file="./hello"; //當前文件夾下的hello文件
fd=open(file, O_RDWR); //先以讀寫方式打開
if(fd<0) //如果該文件不存在,打開失敗了
{
puts("no such file .");
fd=open(file,O_RDWR|O_CREAT,0755); //就加入創建副屬性
if(fd<0)
{
puts("open file err !");
return-1;
}
}
puts("open file success .");
close(fd); //最后記得關閉文件流
puts("close file success .");
return 0;
}