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

时间:2017-03-09 22:09:04

标签: 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 我看到文件.......

我不知道如何捕捉异常或者还有什么可以解决这个问题,任何想法都会很棒。 谢谢, 马丁

2 个答案:

答案 0 :(得分:2)

尝试更改此行:

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

到此:

OutFilename = malloc(1 + root_length + EXT_LENGTH);

为null终止符分配空间。此外,无需投射malloc的返回值。

答案 1 :(得分:0)

DOS对命令行长度有一些严格的限制

因此,当命令行太长时,会出现诸如您遇到的问题。

你真的是说你使用Visual Studio和Windows吗?

DOS的许多限制已经转移到Windows和Visual Studio