计算文件夹中文件使用的字节数时遇到问题。出现段错误错误

发布于 2024-08-19 09:21:57 字数 2181 浏览 2 评论 0原文

我目前正在尝试计算某个目录中文件消耗的字节数。它递归地遍历当前目录上的所有文件夹并计算文件的字节数。

当我递归调用函数 rec_bytes 时,我打印出“Go in”...但是当它返回值时...它会出现段错误。

我在下面的代码中标记了有问题的行。

我认为问题与打开/关闭目录有关。

#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <dirent.h>
#include <string.h>

int rec_Bytes(char path[])
{
    int bytesSum = 0;
    printf("PathX %s\n", path);
    DIR *mydir = opendir(path); // Look in current directory

    struct dirent *entry = NULL;

    while((entry = readdir(mydir))) /* If we get EOF, the expression is 0 and
                                     * the loop stops. */
        {
        if (!isDir(entry->d_name))  // Check to see if the entry is a directory of a file
        {
            char tempPath[] = "";
            strcat(tempPath, path);
            strcat(tempPath,"/");
            strcat(tempPath,entry->d_name);
            int tempSum = fileSize(tempPath);   // Get file size
            bytesSum += tempSum;        // Add to sum
                printf("%s\t%d\n", entry->d_name, tempSum);
        }
        else    // The current entry is a directory
        {
            if ((strcmp((entry->d_name),"..") != 0) && (strcmp((entry->d_name),".")) != 0)
            {
                printf("Directory%s\n", entry->d_name);
                char tempPath[] = "";
                strcat(tempPath, path);
                strcat(tempPath,"/");
                strcat(tempPath,entry->d_name);
                printf("Go in\n");


                int tempSum = rec_Bytes(tempPath); <<<<<< Get segmentation fault here.


                printf("Come Out%d\n", tempSum);
                bytesSum += tempSum;
                    printf("%s\t%d\n", entry->d_name, tempSum);
            }
        }
        }
        closedir(mydir);
    printf("XXXX\t%s\t%d\n", path, bytesSum);
    return bytesSum;
}

// Thanks to : http://cboard.cprogramming.com/cplusplus-programming/117431-how-tell-if-file-directory.html
int isDir(const char* target)
{
   struct stat statbuf;
   stat(target, &statbuf);
   return S_ISDIR(statbuf.st_mode);
}

I am currently trying to count the number of bytes consumed by files in a certain directory. It recursively goes through all the folders on the current directory and counts the bytes of the files.

When I recursively call the function rec_bytes, I print off "Go in"... but when it returns the value... It segfaults.

I labeled the problematic line in the code below.

I think the problem has to do with open/closing directories.

#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <dirent.h>
#include <string.h>

int rec_Bytes(char path[])
{
    int bytesSum = 0;
    printf("PathX %s\n", path);
    DIR *mydir = opendir(path); // Look in current directory

    struct dirent *entry = NULL;

    while((entry = readdir(mydir))) /* If we get EOF, the expression is 0 and
                                     * the loop stops. */
        {
        if (!isDir(entry->d_name))  // Check to see if the entry is a directory of a file
        {
            char tempPath[] = "";
            strcat(tempPath, path);
            strcat(tempPath,"/");
            strcat(tempPath,entry->d_name);
            int tempSum = fileSize(tempPath);   // Get file size
            bytesSum += tempSum;        // Add to sum
                printf("%s\t%d\n", entry->d_name, tempSum);
        }
        else    // The current entry is a directory
        {
            if ((strcmp((entry->d_name),"..") != 0) && (strcmp((entry->d_name),".")) != 0)
            {
                printf("Directory%s\n", entry->d_name);
                char tempPath[] = "";
                strcat(tempPath, path);
                strcat(tempPath,"/");
                strcat(tempPath,entry->d_name);
                printf("Go in\n");


                int tempSum = rec_Bytes(tempPath); <<<<<< Get segmentation fault here.


                printf("Come Out%d\n", tempSum);
                bytesSum += tempSum;
                    printf("%s\t%d\n", entry->d_name, tempSum);
            }
        }
        }
        closedir(mydir);
    printf("XXXX\t%s\t%d\n", path, bytesSum);
    return bytesSum;
}

// Thanks to : http://cboard.cprogramming.com/cplusplus-programming/117431-how-tell-if-file-directory.html
int isDir(const char* target)
{
   struct stat statbuf;
   stat(target, &statbuf);
   return S_ISDIR(statbuf.st_mode);
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

去了角落 2024-08-26 09:21:57

你的问题是这样的行...

char tempPath[] = "";

这将分配一个带有一个字节的缓冲区,该字节是一个空字符。该缓冲区中没有空间容纳任何更长的字符串。

基本上,C 没有动态调整大小的字符串。它具有以空结尾的字符串,这些字符串位于固定大小的字符数组中。当然,当您在完成构建之前无法知道字符串的长度时,这会产生一个问题。

尝试类似...

char tempPath[5000] = "";

作为快速解决方案。另外,查找 strncat - 它不太可能出现段错误。还有一个 printf 变体,但这些天我使用了太多 C++。

编辑

实际上,段错误可能是由于那些 strcats 和 printfs 损坏了堆栈。段错误可能发生在函数尝试返回时。不过,基本问题是字符串缓冲区太小。

哎呀!

真正的快速解决方法是...

char tempPath[5000];
tempPath [0] = 0;

否则,它不会总是在您期望的时候初始化为空字符串。

Your problem is with lines like this...

char tempPath[] = "";

This will allocate a buffer with one byte, that byte being a null character. There is no room in that buffer for any longer string.

Basically, C does not have dynamically resizable strings. It has null terminated strings that live within fixed-size arrays of characters. This creates an issue when you won't know the length of the string until you've finished building it, of course.

Try something like...

char tempPath[5000] = "";

as a quick fix. Also, look up strncat - it's less likely to segfault. There's a printf variant as well, but I use too much C++ these days.

EDIT

Actually, the segfault is probably due to those strcats and printfs corrupting the stack. The segfault is probably when a function tries to return. The basic issue is the too-small string buffers thing, though.

Whoops!

The real quick fix is...

char tempPath[5000];
tempPath [0] = 0;

Otherwise, it won't always get initialised to an empty string when you expect it to.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文