怎样使用C语言列出某个目录下的文件?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了怎样使用C语言列出某个目录下的文件?相关的知识,希望对你有一定的参考价值。

用C语言列出目录下的文件,在linux下可采用readdir()函数来实现,代码实现过程为:

    打开目录

    循环读目录,输出目录下文件

    关闭目录指针

参考代码:

#include <dirent.h>
#include <stdio.h>
int main()

    DIR *dirp; 
    struct dirent *dp;
    dirp = opendir("."); //打开目录指针
    while ((dp = readdir(dirp)) != NULL)  //通过目录指针读目录
        printf("%s\\n", dp->d_name );
          
    (void) closedir(dirp); //关闭目录
    return 0;

在windows下,代码如下:

#include <io.h>
#include <stdio.h>

void printDir( const char* path )

    struct _finddata_t data;
    long hnd = _findfirst( path, &data );    // 查找文件名与正则表达式chRE的匹配第一个文件
    if ( hnd < 0 )
    
        perror( path );
    
    int  nRet = (hnd <0 ) ? -1 : 1;
    while ( nRet >= 0 )
    
        if ( data.attrib == _A_SUBDIR )  // 如果是目录
            printf("   [%s]*\\n", data.name );
        else
            printf("   [%s]\\n", data.name );
        nRet = _findnext( hnd, &data );
    
    _findclose( hnd );     // 关闭当前句柄

void main()

printDir("d:/*.*");

相关函数说明:

long _findfirst( char *filespec, struct _finddata_t *fileinfo );  
// 功  能 : 提供与filespec指定入口泛式匹配的第一个文件.通常后继用_findnext()函数来完成某泛式下的文件遍历.  
// 头文件 : #include <io.h>  
// 参  数 : filespec - 目标文件规范,可以包含通配符  
//          fileinfo - 文件信息buffer  
// 返回值 : 成功返回唯一的搜索句柄  
//          出错返回-1,且设置errno为如下值:  
//          ENOENT 该泛式无法匹配  
//          EINVAL 无效文件名  
int _findnext( long handle, struct _finddata_t *fileinfo );  
// 功  能 : 按照前面_findfirst中的泛式规则,查找下一个符合该泛式的文件,并以此为依据修改fileinfo中的值  
// 头文件 : #include <io.h>  
// 参  数 : long handle - 搜索句柄(通常由紧靠其前的_findfirst()返回)  
//          fileinfo    - 文件信息buffer  
// 返回值 : 成功返回0  
//          出错返回-1
int _findclose( long handle );  
// 功  能 : 关闭搜寻句柄并释放相应资源  
// 头文件 : #include <io.h>  
// 参  数 : long handle - 搜索句柄(通常由紧靠其前的_findfirst()返回)  
// 返回值 : 成功返回0  
//          出错返回-1

参考技术A C语言本身没有提供象dir_list()这样的函数来列出某个目录下所有的文件。不过,利用C语言的几个目录函数,你可以自己编写一个dir_list()函数。首先,头文件dos.h定义了一个find_t结构,它可以描述DOS下的文件信息,包括文件名、时间、日期、大小和属性。其次,C编译程序库中有_dos_findfirst()和_dos_findnext()这样两个函数,利用它们可以找到某个目录下符合查找要求的第一个或下一个文件。dos_findfirst()函数有三个参数,第一个参数指明要查找的文件名,例如你可以用“*.*”指明要查找某个目录下的所有文件。第二个参数指明要查找的文件属性,例如你可以指明只查找隐含文件或子目录。第三个参数是指向一个find_t变量的指针,查找到的文件的有关信息将存放到该变量中。dos_findnext()函数在相应的目录中继续查找由_dos_findfirst()函数的第一个参数指明的文件。_dos_findnext()函数只有一个参数,它同样是指向一个find_t变量的指针,查找到刚文件的有关信息同样将存放到该变量中。利用上述两个函数和find_t结构,你就可以遍历磁盘上的某个目录,并列出该目录下所有的文件,请看下例:#include <stdio.h>#include <direct.h>#include <dos.h>#include <malloc.h>#include <memory.h>#include <string.h>typedef struct find_t FILE_BLOCKvoid main(void);void main(void)FILE_BLOCK f-block; /* Define the find_t structure variable * /int ret_code; / * Define a variable to store the return codes * // * Use the "*.*" file mask and the 0xFF attribute mask to listall files in the directory, including system files, hiddenfiles, and subdirectory names. * /ret_code = _dos_findfirst(" *. * ", 0xFF, &f_block);/* The _dos_findfirst() function returns a 0 when it is successfuland has found a valid filename in the directory. * /while (ret_code == 0)/* Print the file's name * /printf(" %-12s\n, f_block, name);/ * Use the -dos_findnext() function to look本回答被提问者采纳

在C语言编译器目录下执行如下命令

bgiobj egavga,bgiobj命令将驱动程序egavga.bgi转换成egavga.obj的目标文件。这句话到底是什么意思啊?到底如何执行这个命令啊?
还有,我在命令指示符中使用javac命令的时候,显示:error:cannot read ****.java,这是为什么啊?
到底javac命令应该如何用啊?

BGI 驱动程序C源代码
把文件都放到TC目录下执行到命令提示符执行这个命令就偶了。
就像执行汇编的masm命令一样。试试吧,这个我也没用过。
javac的用法:

SYNOPSIS
Javac [ options ] [ sourcefiles ] [ @argfiles ]

Arguments may be in any order.
options :Command-line options.
sourcefiles :One or more source files to be compiled (such as MyClass.java).
@argfiles :One or more files that lists options and source files. The -J options are not allowed in these files.

DESCRIPTION
The javac tool reads class and interface definitions, written in the Java programming language, and compiles them into bytecode class files.
There are two ways to pass source code file names to javac:

For a small number of source files, simply list the file names on the command line.

For a large number of source files, list the the file names in a file, separated by blanks or line breaks. Then use the list file name on the javac command line, preceded by an @ character.
Source code file names must have .java suffixes, class file names must have .class suffixes, and both source and class files must have root names that identify the class. For example, a class called MyClass would be written in a source file called MyClass.java and compiled into a bytecode class file called MyClass.class.
Inner class definitions produce additional class files. These class files have names combining the inner and outer class names, such as MyClass$MyInnerClass.class.

You should arrange source files in a directory tree that reflects their package tree. For example, if you keep all your source files in /workspace, the source code for com.mysoft.mypack.MyClass should be in /workspace/com/mysoft/mypack/MyClass.java.

By default, the compiler puts each class file in the same directory as its source file. You can specify a separate destination directory with -d (see Options, below).

SEARCHING FOR TYPES
When compiling a source file, the compiler often needs information about a type it does not yet recognize. The compiler needs type information for every class or interface used, extended, or implemented in the source file. This includes classes and interfaces not explicitly mentioned in the source file but which provide information through inheritance.
For example, when you subclass java.Applet.Applet, you are also using Applet's ancestor classes: java.awt.Panel, java.awt.Container, java.awt.Component, and java.awt.Object.

When the compiler needs type information, it looks for a source file or class file which defines the type. The compiler searches first in the bootstrap and extension classes, then in the user class path. The user class path is defined by setting the CLASSPATH environment variable or by using the -classpath command line option. (For details, see Setting the Class Path). If you use the -sourcepath option, the compiler searches the indicated path for source files; otherwise the compiler searches the user class path both for class files and source files. You can specify different bootstrap or extension classes with the -bootclasspath and -extdirs options; see Cross-Compilation Options below.

A successful type search may produce a class file, a source file, or both. Here is how javac handles each situation:

Search produces a class file but no source file: javac uses the class file.

Search produces a source file but no class file: javac compiles the source file and uses the resulting class file.

Search produces both a source file and a class file: javac determines whether the class file is out of date. If the class file is out of date, javac recompiles the source file and uses the updated class file. Otherwise, javac just uses the class file.
javac considers a class file out of date only if it is older than the source file.

Note that javac can silently compile source files not mentioned on the command line. Use the -verbose option to trace automatic compilation.

OPTIONS
The compiler has a set of standard options that are supported on the current development environment and will be supported in future releases. An additional set of non-standard options are specific to the current virtual machine and compiler implementations and are subject to change in the future. Non-standard options begin with -X.
Standard Options

-classpath classpath
Set the user class path, overriding the user class path in the CLASSPATH environment variable. If neither CLASSPATH or -classpath is specified, the user class path consists of the current directory. See Setting the Class Path for more details.
If the -sourcepath option is not specified, the user class path is searched for source files as well as class files.

-d directory
Set the destination directory for class files. The destination directory must already exist; javac will not create the destination directory. If a class is part of a package, javac puts the class file in a subdirectory reflecting the package name, creating directories as needed. For example, if you specify -d /home/myclasses and the class is called com.mypackage.MyClass, then the class file is called /home/myclasses/com/mypackage/MyClass.class.
If -d is not specified, javac puts the class file in the same directory as the source file.

Note that the directory specified by -d is not automatically added to your user class path.

-deprecation
Show a description of each use or override of a deprecated member or class. Without -deprecation, javac shows the names of source files that use or override deprecated members or classes.

-encoding encoding
Set the source file encoding name, such as EUCJIS/SJIS. If -encoding is not specified, the platform default converter is used.

-g
Generate all debugging information, including local variables. By default, only line number and source file information is generated.

-g:none
Do not generate any debugging information.

-g:keyword list
Generate only some kinds of debugging information, specified by a comma separated list of keywords. Valid keywords are:
source
Source file debugging information
lines
Line number debugging information
vars
Local variable debugging information

-help
Print a synopsis of standard options.

-nowarn
Disable warning messages.

-source release
Enables support for compiling source code containing assertions.
When release is set to 1.4, the compiler accepts code containing assertions. Assertions were introduced in J2SE 1.4.

When release is set to 1.3, the compiler does not support assertions. The compiler defaults to the 1.3 behavior if the -source flag is not used.

-sourcepath sourcepath
Specify the source code path to search for class or interface definitions. As with the user class path, source path entries are separated by colons (:) and can be directories, JAR archives, or ZIP archives. If packages are used, the local path name within the directory or archive must reflect the package name.
Note that classes found through the classpath are subject to automatic recompilation if their sources are found.

-verbose
Verbose output. This includes information about each class loaded and each source file compiled.
Cross-Compilation Options
By default, classes are compiled against the bootstrap and extension classes of the platform that javac shipped with. But javac also supports cross-compiling, where classes are compiled against a bootstrap and extension classes of a different Java platform implementation. It is important to use -bootclasspath and -extdirs when cross-compiling; see Cross-Compilation Example below.

-target version
Generate class files that will work on VMs with the specified version. The default is to generate class files to be compatible with the 1.2 VM in the Java 2 SDK, with one exception. When the -source 1.4 option is used, the default target is 1.4. The versions supported by javac are:

1.1
Ensure that generated class files will be compatible with 1.1 and VMs in the Java 2 SDK.
1.2
Generate class files that will run on VMs in the Java 2 SDK, v 1.2 and later, but will not run on 1.1 VMs. This is the default.
1.3
Generate class files that will run on VMs in the Java 2 SDK, v 1.3 and later, but will not run on 1.1 or 1.2 VMs.
1.4
Generate class files that are compatible only with 1.4 VMs.

-bootclasspath bootclasspath
Cross-compile against the specified set of boot classes. As with the user class path, boot class path entries are separated by colons (:) and can be directories, JAR archives, or ZIP archives.

-extdirs directories
Cross-compile against the specified extension directories. Directories is a colon-separated list of directories. Each JAR archive in the specified directories is searched for class files.
Non-Standard Options

-X
Display information about non-standard options and exit.

-Xstdout filename
Send compiler messages to the named file. By default, compiler messages go to System.err.

-Xswitchcheck
Checks switch blocks for fall-through cases and provides a warning message for any that are found. Fall-through cases are cases in a switch block, other than the last case in the block, whose code does not include a break statement, allowing code execution to "fall through" from that case to the next case. For example, the code following the case 1 label in this switch block does not contain a break statement:
switch (x)
case 1:
System.out.println("1");
// No break; statement here.
case 2:
System.out.println("2");


If the -Xswtichcheck flag were used when compiling this code, the compiler would emit a warning about "possible fall-through into case," along with the line number of the case in question.
The -J option
-Joption
Pass option to the java launcher called by javac. For example, -J-Xms48m sets the startup memory to 48 megabytes. Although it does not begin with -X, it is not a `standard option' of javac. It is a common convention for -J to pass options to the underlying VM executing applications written in Java.
Note that CLASSPATH, -classpath, -bootclasspath, and -extdirs do not specify the classes used to run javac. Fiddling with the implementation of the compiler in this way is usually pointless and always risky. If you do need to do this, use the -J option to pass through options to the underlying java launcher.

COMMAND LINE ARGUMENT FILES
To shorten or simplify the javac command line, you can specify one or more files that themselves contain arguments to the javac command (except -J options). This enables you to create javac commands of any length on any operating system.
An argument file can include javac options and source filenames in any combination. The arguments within a file can be space-separated or newline-separated. Filenames within an argument file are relative to the current directory, not the location of the argument file. Wildcards (*) are not allowed in these lists (such as for specifying *.java). Use of the '@' character to recursively intERPret files is not supported. The -J options are not supported because they are passed to the launcher, which does not support argument files.

When executing javac, pass in the path and name of each argument file with the '@' leading character. When javac encounters an argument beginning with the character `@', it expands the contents of that file into the argument list.

Example - Single Arg File
You could use a single argument file named "argfile" to hold all javac arguments:
C:> javac @argfile

This argument file could contain the contents of both files shown in the next example.
Example - Two Arg Files
You can create two argument files -- one for the javac options and the other for the source filenames: (Notice the following lists have no line-continuation characters.)
Create a file named "options" containing:

-d classes
-g
-sourcepath \java\pubs\ws\1.3\src\share\classes

Create a file named "classes" containing:

MyClass1.java
MyClass2.java
MyClass3.java

You would then run javac with:
C:> javac @options @classes

Example - Arg Files with Paths
The argument files can have paths, but any filenames inside the files are relative to the current working directory (not path1 or path2):
C:> javac @path1\options @path2\classes

EXAMPLES
Compiling a Simple Program
One source file, Hello.java, defines a class called greetings.Hello. The greetings directory is the package directory both for the source file and the class file and is off the current directory. This allows us to use the default user class path. It also makes it unnecessary to specify a separate destination directory with -d.
% ls
greetings/
% ls greetings
Hello.java
% cat greetings/Hello.java
package greetings;

public class Hello
public static void main(String[] args)
for (int i=0; i < args.length; i++)
System.out.println("Hello " + args[i]);



% javac greetings/Hello.java
% ls greetings
Hello.class Hello.java
% java greetings.Hello World Universe Everyone
Hello World
Hello Universe
Hello Everyone

Compiling Multiple Source Files
This example compiles all the source files in the package greetings.
% ls
greetings/
% ls greetings
Aloha.java GutenTag.java Hello.java Hi.java
% javac greetings/*.java
% ls greetings
Aloha.class GutenTag.class Hello.class Hi.class
Aloha.java GutenTag.java Hello.java Hi.java

Specifying a User Class Path
Having changed one of the source files in the previous example, we recompile it:
% pwd
/examples
% javac greetings/Hi.java

Since greetings.Hi refers to other classes in the greetings package, the compiler needs to find these other classes. The example above works, because our default user class path happens to be the directory containing the package directory. But suppose we want to recompile this file and not worry about which directory we're in? Then we need to add /examples to the user class path. We can do this by setting CLASSPATH, but here we'll use the -classpath option.
% javac -classpath /examples /examples/greetings/Hi.java

If we change greetings.Hi again, to use a banner utility, that utility also needs to be Accessible through the user class path.
% javac -classpath /examples:/lib/Banners.jar \
/examples/greetings/Hi.java

To execute a class in greetings, we need access both to greetings and to the classes it uses.
% java -classpath /examples:/lib/Banners.jar greetings.Hi

Separating Source Files and Class Files
It often makes sense to keep source files and class files in separate directories, especially on large projects. We use -d to indicate the separate class file destination. Since the source files are not in the user class path, we use -sourcepath to help the compiler find them.

% ls
classes/ lib/ src/
% ls src
farewells/
% ls src/farewells
Base.java GoodBye.java
% ls lib
Banners.jar
% ls classes
% javac -sourcepath src -classpath classes:lib/Banners.jar \
src/farewells/GoodBye.java -d classes
% ls classes
farewells/
% ls classes/farewells
Base.class GoodBye.class

Note that the compiler compiled src/farewells/Base.java, even though we didn't specify it on the command line. To trace automatic compiles, use the -verbose option.
Cross-Compilation Example
Here we use the Java 2 SDK javac to compile code that will run on a 1.1 VM.
% javac -target 1.1 -bootclasspath JDK1.1.7/lib/classes.zip \
-extdirs "" OldCode.java

The -target 1.1 option ensures that the generated class files will be compatible with 1.1 VMs. In the Java 2 SDK javac compiles for 1.2 by default.
The Java 2 SDK's javac would also by default compile against its own bootstrap classes, so we need to tell javac to compile against JDK 1.1 bootstrap classes instead. We do this with -bootclasspath and -extdirs. Failing to do this might allow compilation against a Java 2 Platform API that would not be present on a 1.1 VM and fail at runtime.
参考技术A TC怎么把java都牵扯进来了,越来越不懂了。。。

以上是关于怎样使用C语言列出某个目录下的文件?的主要内容,如果未能解决你的问题,请参考以下文章

怎样删除C:\Program Files下的文件夹?

如何列出目录下的所有文件

怎样在Ubuntu里设置vim加亮显示c语言函数名?

WINDOWS操作系统下的C语言头文件存放在哪个目录中?

怎样安装C语言中的graphics.h以及哪里可下载吗?

怎样把c语言程序和文件存入同一目录中?