戏水游鱼的blog

  IT博客 :: 首页 :: 联系 :: 聚合  :: 管理
  2 Posts :: 0 Stories :: 1 Comments :: 0 Trackbacks
    开个博客,记录下自己的学习历程。我尽量写的详细点,好好学学。   
    参考书:《linux 编程技术详解》人民邮电出版社 杜华。                
                 《The c programme language》
   
 linux 的文件操作一般分打开,操作,关闭三个阶段。主要用的函数有open,read,fork,close等这几个函数。关于函数的具体用法,可以参考linux编程手册(有个中文版)。

     代码:
  1 #include <stdio.h>
  2 #include <sys/types.h>
  3 #include <sys/stat.h>
  4 #include <fcntl.h>
  5
  6 int main()
  7 {
  8     char test;
  9     int fd;   //接受文件描述符(一个很小的整数,返回打开文件的信息)
 10
 11     if((fd = open("test.dat",O_RDONLY)) == -1){    //打开文件,以只读方式打开。失败,给出提示
 12         perror("Cannot open the test.dat");    
 13     }
 14
 15     if(fork() == -1){   //用fork创建一个子进程(父进程返回子进程的进程号,子进程返回0)
 16         perror("Cannot Create the child process");
 17         return 1;
 18     }
 19
 20     read(fd,&test,1); //读取test.dat文件中的一个字符,将其保存在名为test中
 21
 22     //输出运行结果,函数getpid获得进程的进程号
 23     printf("Process ID: %ld readthe character : %c\n",(long)getpid(),test);
 24
 25     //关闭文件,注意这里实际上是关闭两次(父子)
 26     close(fd);
 27
 28     return 0;
 29 }

int open(const char *pathname, int flag); 返回一个文件标识符
ssize_t read(int fd, int *buf, int count);   //read函数从fd中读取count个字节,放入buf中。
pid_t fork(void);
printf: %c   单个字符
           %d  十进制整数
           %e  科学计数法的十进制表示
           %f  浮点数
           %s  字符串
int close(int fd);  成功0,失败-1
posted on 2008-05-08 15:29 戏水游鱼 阅读(270) 评论(0)  编辑 收藏 引用
只有注册用户登录后才能发表评论。