嵌入式Linux C 系统开发

注意:C语言程序设计:无OS语法!

一.Linux C系统开发初了解

  • Linux系统空间划分:用户空间,内核空间。
  • 划分空间的目的:
    保护内核空间不能被用户空间随便访问。
  • 用户空间如何访问内核空间?
    答:必须发送系统调用。
  • 如何发生系统调用?
    答:调用操作系统提供的函数接口——API。

二.开发函数

主要有create.write.open.read,下面简单介绍一下

#include "stdio.h"
#include "unistd.h"
#include "string.h"
#include "stdlib.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#define MAXLEN 1000
int main(int argc,char **argv)
{
    int srcfile; //源文件 描述符
    int dstfile; //目标文件 描述符
    char buf[MAXLEN+1]; 
    char dstfile_path[100];  //目标文件路径
    char current_path[100];  //当前路径
    int n=0;
    if(argc != 3)  
    {
        printf("usage:a.out srcfile_pathname dstfile_path\n");
        exit(0);
    }
    memset(current_path,0,sizeof(current_path));
    getcwd(current_path,sizeof(current_path)-1);  //获取当前路径
    memset(dstfile_path,0,sizeof(dstfile_path));
    sprintf(dstfile_path,"%s",argv[2]);  //获取目标路径,在命令行输入
    if(memcmp(current_path,dstfile_path,strlen(dstfile_path)) == 0)  //比较如果当前路径和目标路径一样,则错误
    {
        printf("error: srcfile and dstfile are the same!\n");
        exit(0);
    }
    
    sprintf(dstfile_path,"%s%s",argv[2],argv[1]);  //得到目标完成路径名

    if((srcfile=open(argv[1],O_RDONLY,0)) < 0)  //打开源文件
       printf("open [%s] error!\n",argv[1]);
    if((dstfile=open(dstfile_path,O_WRONLY|O_CREAT,0)) < 0)  //打开和创建目标文件
       printf("open [%s] error!\n",dstfile_path);

    memset(buf,0,sizeof(buf));  //开始拷贝
    while((n=read(srcfile,buf,MAXLEN)) > 0)
    {
      write(dstfile,buf,n);
    }
    if(n<0)
      {
        printf("read [%s] error!\n",argv[1]);
        exit(0); 

      }
    chmod(dstfile_path,S_IRUSR|S_IWUSR);  //复制完后改变权限,这样才能读写
    close(srcfile);  //关闭文件
    close(dstfile);
    return 0;
    exit(0);
    
}

假如文件名为cp.c
用gcc cp.c编译生成a.out目标文件
然后在终端输入 ./a.out cp.c  目标文件夹路径,就可以将cp.c拷贝到目标文件夹路径底下了。

读懂这段代码我相信大家能够很好的了解这四个函数。

你可能感兴趣的:(嵌入式Linux C 系统开发)