c - fopen 和 fopen_s 似乎在长文件名上崩溃

标签 c exception fopen

我正在使用 visual studio 2013 构建一个 c 应用程序

代码看起来是这样的-

int main( int argc, char *argv[] )
{
    char *InFilename = NULL;
    char *OutFilename = NULL;
    int ff_count; // counts the number of successive 0xff's read from the file buffer
    int fpga_end, nios_start, nios_end; // used to report the size of each region
    int file_length, file_index, temp_length, new_file_length;
    int root_length;
    int result;

    FILE *infile = NULL;
    FILE *outfile = NULL;

    printf("Start JIC 2 rbf\r\n");

    if ((argc != 2))
    {
        printf("\r\n\r\nV1.2 - Usage: <jic2rbf> <name of jicfile> \r\n");
        printf("\r\n This program strips out the header info at the top of the file\r\n");
        printf("\r\n  and most of the ff's at the bottom.  \r\n");
        exit(1);
    }

    //
    // Extract the name of the input file up to the '.' and use it to create the output file name with a .rbf extension.
    //

    InFilename = argv[1];
    root_length = strcspn(InFilename,".");

    printf("Root len = %d\r\n",root_length);

    OutFilename = (char *)malloc(root_length+EXT_LENGTH);
    memcpy(OutFilename,InFilename,root_length);
    OutFilename[root_length] = 0;
    strcat(OutFilename,".rbf");

    printf("In file to be used %s\r\n", InFilename);
    printf("Out file to be used %s\r\n", OutFilename);

    result = fopen_s(&outfile, OutFilename, "wb");
    if (result)
    {
        printf("Cannot open this file %s\r\n - 0x%x", OutFilename, result);
        return 0;
    }
    printf("Open In - %d\r\n",result);

如果我使用 - 从 dos 命令行调用此可执行文件

E:/projects/Q4300_Hdcp/q_series_hdcp_base/fpga/q_series_hdcp_tx_dual_singleHID/par/q_series_hdcp_tx_dual_singleHID/output_files/q_series_hdcp_tx_dual_singleHID_elf.jic

整个应用程序工作

如果我使用以下命令行调用应用程序 -

E:/projects/Q4300_Hdcp/q_series_hdcp_base/fpga/q_series_hdcp_tx_dual_fpga/par/q_series_hdcp_tx_dual_fpga/output_files/q_series_hdcp_tx_dual_fpga_elf.jic

我没有看到 printf("Open In - %d\r\n",result); 输出。该应用程序似乎崩溃了。 我认为这可能是文件名中的某种缓冲区溢出,但较短的文件名有效......如果我 cd 到包含文件的目录并使用命令行 调用q_series_hdcp_tx_dual_fpga_elf.jic 有效。 如果我目录文件 - E:/projects/Q4300_Hdcp/q_series_hdcp_base/fpga/q_series_hdcp_tx_dual_fpga/par/q_series_hdcp_tx_dual_fpga/output_files/q_series_hdcp_tx_dual_fpga_elf.jic 我看到了文件…………

我不知道如何捕获异常或解决此问题的其他方法,任何想法都会很棒。 谢谢, 马丁

最佳答案

尝试改变这一行:

OutFilename = (char *)malloc(root_length+EXT_LENGTH);

为此:

OutFilename = malloc(1 + root_length + EXT_LENGTH);

为空终止符分配空间。此外,无需强制转换 malloc 的返回值。

关于c - fopen 和 fopen_s 似乎在长文件名上崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42706416/

相关文章:

c - C 中的二叉搜索树,段错误

asp.net - 记录异常时忽略 ThreadAbortException

C# System.InvalidOperationException : The current TransactionScope is already complete

javascript - 如何使用php将PDF文件嵌入到iframe中

c - 初学者关于C中fopen的另一个问题

c - UndefinedBehaviorSanitizer 因为空指针

c - 为什么不将重定向输入视为命令行参数?

c - 返回指向返回相同类型的函数的函数指针

java - 如何添加 e.getmessage() 作为 java 方法的返回

PHP fopen 'x+' 在 ubuntu 上不工作