|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 moonbeams 于 2023-2-27 11:44 编辑
源代码如下:
- #include<io.h>
- #include<direct.h>
- #include<stdio.h>
- #include<stdlib.h>
- #include<string.h>
- #define MAX 256
- long total;
- int countLines(const char *filename);
- void findAllCodes(const char *path);
- void findAllFiles(const char *path);
- int countLines(const char *filename)
- {
- FILE *fp;
- int count = 0;
- int temp;
- if((fp = fopen(filename, "r")) == NULL)
- {
- fprintf(stderr, "Can not open the file:%s\n",filename);
- return 0;
- }
- while((temp = fgetc(fp)) != EOF)
- {
- if(temp == '\n')
- {
- count++;
- }
- }
- fclose(fp);
- return count;
- }
- void findAllCodes(const char *path)
- {
- struct _finddata_t fa;
- long handle;
- char thePath[MAX],target[MAX];
- strcpy(thePath,path);
- if((handle = _findfirst(strcat(thePath,"/*.c"),&fa))!= -1L)
- {
- do
- {
- sprintf(target, "%s\\%s",path, fa.name);/////////////////
- total += countLines(target);
- }while(_findnext(handle, &fa) == 0);
- }
- _findclose(handle);
- }
- void findALLDirs(const char *path)
- {
- struct _finddata_t fa;
- long handle;
- char thePath[MAX];
- strcpy(thePath,path);
- if((handle = _findfirst(strcat(thePath, "/*"),&fa)) == -1L)
- {
- fprintf(stderr, "The path %s is wrong!\n",path);
- return;
- }
- do
- {
- if(!strcmp(fa.name,".")|| !strcmp(fa.name,".."))
- continue;
- if( fa.attrib == _A_SUBDIR)
- {
- sprintf(thePath, "%s\\%s", path, fa.name);///////////////////
- findAllCodes(thePath);
- findALLDirs(thePath);
- }
- }while(_findnext(handle, &fa) == 0);//会在这里报错:Segmentation fault;权限不够,发不了图片
- _findclose(handle);
- }
- int main()
- {
- char path[MAX] = ".";
- printf("计算中...\n");
- findAllCodes(path);
- findALLDirs(path);
- printf("目前你总共写了 %ld 行代码!\n\n", total);
- system("pause");
- return 0;
- }
复制代码
权限不够发不了图片,报错内容在上面注释了
根据代码中的注释,“Segmentation fault”是一个权限不够的错误。通常情况下,访问了系统保护内存区域导致的。但是,在这个实现中,这种错误可能会发生在进行目录遍历查找时。具体来说,当处理嵌套目录的过程中,可能会出现路径超长的情况,导致数组越界或者缓冲区溢出,从而访问到系统保护内存区域,使程序中止并报“Segmentation Fault”错误。
为了改正这一点,可以考虑使用更加安全的字符串拼接方式,例如 strncat 或者 snprintf 函数,来保证拼接后字符串长度不会超过指定的范围。此外,还可以在代码开头 #define MAX 更改为更大的值,以便能够容纳更长的路径名。
|
|