用man open指令查询用法 其也如此 没有就man 2
结果展示 不懂自己翻译(注意形参,返回值)
SYNOPSIS
//头文件
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
//函数
int open(const char *pathname, int flags);//文件名称,打开模式
int open(const char *pathname, int flags, mode_t mode);
int creat(const char *pathname, mode_t mode);
int openat(int dirfd, const char *pathname, int flags);
int openat(int dirfd, const char *pathname, int flags, mode_t mode);
Feature Test Macro Requirements for glibc (see feature_test_macros(7)):
openat():
Since glibc 2.10:
_POSIX_C_SOURCE >= 200809L
Before glibc 2.10:
_ATFILE_SOURCE
打开模式:
O_APPEND以追加方式打开
O_RDWR以可读可写的方式打开
O_RDONLY以只读方式打开
O_WRONLY以只写方式打
O_CREAT如果文件不存在则创建
O_TRUNC如果文件存在则截短为0
打开文件写入文件,和读取文件
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int fg=open("a.c",O_RDWR);
if(-1==fg)
{
perror("open file error");
return 0;
}
char *p_data=(char *)malloc(100);
memset(p_data,0,100);
/*
int n=read(fg,p_data,99);
printf("Holle word %d\n",fg);
printf("n:%d\n",n);
printf("p_data:%s",p_data);
int n;
while( n=read(fg,p_data,99))
{
printf("n:%d\n",n);
printf("p_data:%s",p_data);
memset(p_data,0,100);
}
close(fg);
*/
int fd=open("b.c",O_RDWR);
if(-1==fd)
{
perror("open file error");
return 0;
}
char *buf="hello world";
write(fd,buf,5);
close(fd);
return 0;
ps:
1.打开文件后可以直接写入close来关闭文件,需要的带代码写在中间,注意close的头文件添加。
2.在写文件的时候要注意如果打开模式不设置追加方式打开,则每次写文件的时候都会从第一个字符开始覆盖写入。
3.在读文件read()时注意读取的大小不能超过设置空间的大小,设置空间可以用以上程序的指针方式(注意定义空间后要清零,在循环读取时也要记得清零)也可以初始化一个char a[]={0};的数组来实现,最大1024.
4.read返回值是读取的个数,open的返回值的0成功-1失败