Chinaunix首页 | 论坛 | 博客
  • 博客访问: 5086270
  • 博文数量: 553
  • 博客积分: 13864
  • 博客等级: 上将
  • 技术积分: 11041
  • 用 户 组: 普通用户
  • 注册时间: 2011-11-28 21:25
个人简介

个人Blog: hhktony.com

文章分类

全部博文(553)

文章存档

2015年(1)

2014年(2)

2013年(12)

2012年(384)

2011年(154)

分类: LINUX

2012-01-30 19:20:32

在Linux系统内所有东西都是以文件的形式来表示的,除一般的磁盘文件外,还有设备文件,如硬盘、声卡、串口、打印机等。设备文件又可分为字符设备文件(character devices)和块设备文件(block devices)。使用man hier命令可以查看Linux文件系统的分层结构。文件的处理方法一般有五种,分别是:

    open,打开一个文件或设备。
    close,关闭一个打开的文件或设备。
    read,从一个打开的文件或者设备中读取信息。
    write,写入一个文件或设备。
    ioctl,把控制信息传递给设备驱动程序

open,close,read,write和ioctl都是低级,没有缓冲的文件操作函数,在实际程序开发中较少使用,一般我们使用标准I/O函数库来处理文件操作。如:fopen,fclose,fread,fwrite,fflush等。在使用标准I/O库时,需用到stdio.h头文件。
一些常用的文件和目录维护函数:chmod、chown、unlink、link、symlink、mkdir、rmdir、chdir、getcwd、opendir,closedir、readdir、telldir、seekdir等。
fcntl用于维护文件描述符,mmap用于分享内存。
创建文档并输入信息的示例代码:
#include
main(void)
        {
        FILE *fp1;
        char c;

        fp1 = fopen("text.txt","w");
        while ((c = getchar())!= '\n')
                putc(c,fp1);
        fclose(fp1);
        }

显示路径的示例代码

#include
#include
#include
#include
#include
#include

int main(int argc, char *argv[])
{
        char *topdir = ".";
        if (argc >= 2)
                topdir = argv[1];

        printf("Directory scan of %s\n", topdir);
        printdir(topdir,0);
        printf("done.\n");

        exit(0);
}

printdir(char *dir, int depth)
{
        DIR *dp;
        struct dirent *entry;
        struct stat statbuf;

        if((dp = opendir(dir)) == NULL)
        {
                fprintf(stderr,"cannot open directory:%s\n",dir);
                return;
        }
        chdir(dir);
        while((entry = readdir(dp)) != NULL)
        {
                lstat(entry->d_name,&statbuf);
                if(S_ISDIR(statbuf.st_mode))
                {
                        if(strcmp(".",entry->d_name) == 0 || strcmp("..",entry->d_name) == 0)
                                continue;
                        printf("%*s%s/\n",depth,"",entry->d_name);
                        printdir(entry->d_name,depth+4);
                }
                else printf("%*s%s\n",depth,"",entry->d_name);
        }
        chdir("..");
        closedir(dp);
}

阅读(1766) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~