访问违规写位置0x01140000

问题描述 投票:0回答:1

我对 C 比较陌生,但遇到了一个问题。我想列出给定的目录并搜索所有文件或子目录,并记下文件的名称以及最后一次访问它的时间。但是每次在 sprintf_s() 之后它都会给我访问冲突。我认为这与我的指针作为递归函数中的参数有关。 所以这是我的代码:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<errno.h>
#include<windows.h>
#include<direct.h>
#include<stdbool.h>
#define __STDC_WANT_LIB_EXT1__ 1

bool ListFromDirectory(const char* sDir) {//recursive functions for listing through the directory
    WIN32_FIND_DATA fdFile;
    HANDLE hFind = NULL;

    char sPath[2048];

    //Specify a file mask. *.*
     sprintf_s(sPath, "%s\\*.*", sDir);
    if ((hFind = FindFirstFile(sPath, &fdFile)) == INVALID_HANDLE_VALUE)
    {
        printf("Path not found: [%s]\n", sDir);
        return false;
    }

    do
    {
        //Find first file will always return "."
        //    and ".." as the first two directories.
        if (strcmp(fdFile.cFileName, ".") != 0
            && strcmp(fdFile.cFileName, "..") != 0)
        {
            LPSYSTEMTIME lpSystemTime;

            //Is the entity a File or Folder?
            if (fdFile.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
            {
                printf("Directory: %s\n", sPath);
                ListFromDirectory(sPath);
            }
            else {
                printf("File: %ls\n", fdFile.cFileName);
                FILETIME localFiletime;
                if (FileTimeToLocalFileTime(&fdFile.ftLastWriteTime, &localFiletime)) {
                    SYSTEMTIME sysTime;
                    if (FileTimeToSystemTime(&localFiletime, &sysTime)) {
                        printf("%ls is last modified at %.2d-%.2d-%4d %.2d:%.2d:%.2d\n",
                            fdFile.cFileName,                            
                            sysTime.wMonth, sysTime.wDay, sysTime.wYear,
                            sysTime.wHour, sysTime.wMinute, sysTime.wSecond);
                    }
                }
            }
        }
    } while (FindNextFile(hFind, &fdFile)); //Find the next file.

    FindClose(hFind);

    return true;
}
int main() {
    char c[12] = "E:\\Windows\\";
    ListFromDirectory(c);
    return 0;
}

sprintf_s()后的错误:Exception thrown at 0x7A85EF8C (ucrtbased.dll): 0xC0000005: Access violation writing location 0x00760000.

c file directory access-violation
1个回答
1
投票

您忽略了编译器警告和

sprintf_s
的手册页,其中指出您需要传递缓冲区大小,所以

sprintf_s(sPath, "%s\\*.*", sDir);

应该是

sprintf_s(sPath, sizeof sPath, "%s\\*.*", sDir);

编译器还给出了很多关于您在格式字符串中使用的类型说明符的警告。

© www.soinside.com 2019 - 2024. All rights reserved.