【发布时间】:2021-05-26 20:17:10
【问题描述】:
我刚开始用 C 语言编写,我遇到了一个小问题,与算法有关,而不是语言的特性。
在我的程序中,任务是在_符号后插入文件大小,如果文件名中有一个。
我不太明白这是怎么实现的,也许有人会告诉你,有一个现成的算法可以解决这个问题,在字符串中插入一个数字(字符数组)
这是我的代码示例,其中说明了在哪里以及正在做什么:
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <string.h>
int main(){
DIR * p;
p = opendir("."); // Open catalog
if(p!=NULL){ // check on error
struct dirent * dir;
while((errno=0, dir=readdir(p))){ // Reading catalog
struct stat infoAboutFile;
int res = stat(dir->d_name, &infoAboutFile);
if(res==0){ // check on error
if(S_ISREG(infoAboutFile.st_mode)){ // Check on regular files
char str[256];
strcpy(str,dir->d_name);
int size = infoAboutFile.st_size; //Size file
printf("\n");
}
}else{
perror("Errors in Stat");
}
}
if(errno!=0){ // check on error
perror("Errors in Readdir");
}
int res = closedir(p);
if(res==-1){ // check on errorr
perror("Errors in Closedir");
}
}else{
perror("Errors in Opendir");
}
return 0;
}
【问题讨论】:
-
而不是
char str[256];,您可能想要使用char str[PATH_MAX](PATH_MAX 在中定义)