Get the number of files and file name in the folder in C language

Overview

** The method of getting advice in the comments seemed to be the best, so please refer to that **

I'm sorry I left it

~~ I was a little worried, so I wrote a program to get the number of files and the file name in the specified folder. ~~ ~~ Filenames are stored in a two-dimensional dynamic array. ~~ Specify the folder you want to check in ~~ chdir (comment out if it is in the same hierarchy as the program) ~~ ~~ Only for Windows (If you change the instruction in System, you can probably do it in Linux ()) ==

~~ * Since tmp.txt is temporarily generated and deleted, if tmp.txt exists in the same hierarchy as the program, change the file name in the program to an appropriate one. ~~

~~ ** I think there is probably a better way, so I would appreciate it if you could let me know ... ** ~~

~~ I'm tired when writing, so the sentences are stiff ... ((((((~~~)

Source

#include<stdio.h>
#include<string.h>

int main(){
	char **file_name;
	int i,len,file_num=0;
	char input[128];
	FILE *fp;
	
	//■■■■■■■■■■■■■■■■■■■■■■■■■■■
	//Folder name to look up
	chdir("a");
	system("dir /B > ../tmp.txt");
	chdir("../");
	
	fp=fopen("tmp.txt","r");
	while(fgets(input,64,fp)!=NULL){
		file_num++;
	}
	fseek(fp,0,SEEK_SET);
	file_name = (char**)malloc(sizeof(char*)*file_num);
	for(i=0;i<file_num;i++){
		fgets(input,64,fp);
		len=strlen(input);
		file_name[i]=(char *)malloc(sizeof(char)*len);
		sprintf(file_name[i],"%s",input);
	}
	fclose(fp);
	remove("tmp.txt");
	//■■■■■■■■■■■■■■■■■■■■■■■■■■■
	
	//display
	printf("number of files:%d\n",file_num);
	for(i=0;i<file_num;i++){
		printf("%s\n",file_name[i]);
	}
	
	//release
	for(i=0;i<file_num;i++){
		free(file_name[i]);
	}
	free(file_name);
	
	return 0;
}

Recommended Posts