linux 系统编程1

在Linux系统中一切皆文件,在Linux系统中一共有7种文件类型:1.普通文件    2.目录文件     3.字符设备文件    4.块设备文件    5.链接文件     6.管道文件     7.套接字文件

 

打开/创建一个文件

       int open(const char *pathname,int flags);

       int open(const char *pathname,int flags,mode_t mode);

       fd=open();

       fd为返回值 是文件描述符 即file descriptor 是一个非负整数。

      pathname :文件路径

      flags:打开方式    O_RDONLY   O_WRONLY   O_RDWR   O_CREAT    O_TRUNC   O_APPEND......

      mode:新文件的访问权限,只有在O_CREAT 时才有意义

     文件描述符的分配规则:最小未被占用的

     fd一般等于3

    0:stdin     标准输入

    1:    stdout    标准输出

     2:  stderr     标准错误

      文件创建掩码  umask();

                                                                                                                 

#include<stdio.h>

#include<stdlib.h>

#include<string.h>

#include<sys/types.h>

#include<sys/stat.h>

#include<unistd.h>

#include<fcntl.h>

int main(int argc,char **argv)

{

        int fd;

       fd=open(argv[1],O_WRONLY|O_CREAT|O_TRUNC,0777);

//O_CREAT 如果文件不存在则创建
 //O_TRUNC 如果文件存在则清零0
 //O_APPEND 如果文件存在则定位到文件末尾    
 //open的第三个参数,在打开方式中有O_CREAT有意义,指定被创建文件的权限

      if(fd<0)

    {

          perror("open()");

          return -1;

   }

     printf("fd=%d\n",fd);

     char *p="hello world";

     write(fd,p,strlen(p));

     close(fd);

    return 0;

}

猜你喜欢

转载自blog.csdn.net/d1306937299/article/details/48413047