打印目录中文件名字的代码类似于linux中ls命令的代码(C/C++)
本次实验是打印目录下文件的名字的代码。
实验环境为阿里云ubuntu16.04 编译器是gcc5.4版本。
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <dirent.h>
#define ERR_EXIT(m) \
do \
{ \
perror(m); \
exit(EXIT_FAILURE); \
}while(0)
int main()
{
DIR *dir = opendir(".");
struct dirent *de;
while((de = readdir(dir))!=NULL)
{
if(strncmp(de->d_name,".",1) == 0)
{
continue;
}
printf("%s\n",de->d_name);
}
closedir(dir);
return 0;
}
实验结果