Chinaunix

标题: c文件目录判断 [打印本页]

作者: 三月开桃花    时间: 2012-02-17 12:27
标题: c文件目录判断
C 如何判断一个FILE是文件还是目录?
求解答.
作者: bruceteen    时间: 2012-02-17 13:39
刚写的,你改改吧
  1. #include <stdio.h>
  2. #include <errno.h>
  3. #include <sys/types.h>
  4. #include <sys/stat.h>

  5. void foo( const char* filename )
  6. {
  7.         struct _stat buf;
  8.         int r = _stat( filename, &buf );
  9.         if( r == 0 )
  10.         {
  11.                 if( buf.st_mode & _S_IFDIR )
  12.                         printf( "folder\n" );
  13.                 else
  14.                         printf( "file\n" );
  15.         }
  16.         else
  17.         {
  18.                 if( errno == ENOENT )
  19.                         printf( "nonexistent\n" );
  20.                 else
  21.                         printf( "error" );
  22.         }
  23. }

  24. int main()
  25. {
  26.         foo( "c:\\1111.bmp" ); // nonexistent
  27.         foo( "c:\\1.bmp" );    // file
  28.         foo( "C:\\Qt" );       // folder

  29.         return 0;
  30. }
复制代码

作者: 三月开桃花    时间: 2012-02-17 13:43
回复 2# bruceteen


    _stat( filename, &buf );
这个是什么包里,我想知道C是怎么判断的?
作者: ruifengzhangyi    时间: 2012-02-17 14:07
很怪异的方法,直接判断指针不行吗,如果是Linux下判断第一个字母是/
如果是windows判断第2到第3个是:\
作者: 三月开桃花    时间: 2012-02-17 14:13
求个用C提供的基本函数例子
作者: walleeee    时间: 2012-02-17 14:15
http://blog.chinaunix.net/space. ... blog&id=1568653
作者: 三月开桃花    时间: 2012-02-17 14:23
回复 6# walleeee

看了,FILE里没有这个标志位么?

为什么还要另外加一个struct?

作者: walleeee    时间: 2012-02-17 14:25
回复 7# 三月开桃花


    这个是设计问题。你总不能怪c标准吧。如果是我,我一般就直接用系统api来查询这些信息,越过libc
作者: 三月开桃花    时间: 2012-02-17 14:37
最近不太忙,想熟悉下C基础
还是想在它的基础上做

作者: gpf626487    时间: 2012-02-17 17:01
看来LZ没有了解过系统编程,这是最基本的struct stat ,struct dirent 结构
作者: cokeboL    时间: 2012-02-17 19:08
回复 5# 三月开桃花


    stat还是fstat来着,APUE上,自己找下
作者: cj_gameboy    时间: 2012-02-17 20:45
提示: 作者被禁止或删除 内容自动屏蔽




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2