2
votes
#include<stdio.h>
#include<stdlib.h>
int main(int argc, char *argv[])
{
FILE *source_fp, *content_fp;
int ch;
if(!(source_fp=fopen(argv[1],"wb")))
{
    printf("can't open file\n");
    return 0;
}

for(int i = 2 ; i < argc ; i++)
{
    if(!(content_fp=fopen(argv[i],"r")))
        printf("can't find file%s\n", argv[i]);
    else
    {
        while(ch = fgetc(source_fp))
        {
            fputc(ch,source_fp);
        }
        fclose(content_fp);
    } 
}
fclose(source_fp);
} 

I get the following error messages when running this program:

Debug Assertion Failed!

Program: ...ments\Visual Studio 2015\Projects\Project9\Debug\Project9.exe File: minkernel\crts\ucrt\src\appcrt\stdio\fopen.cpp Line: 30

Expression: file_name != nullptr

For information on how your program can cause an assertion failure, see the Visual C++ documentation on asserts.

(Press Retry to debug the application)

How do I fix this issue?

1
C and file_name = nullptr? Must be MSVC. And you're not checking if argv[1] is non-null. - Andrew Henle
How many command line parameters do you pass, - 0___________
Are you passing the right arguments to your program? You don't check if argc is at least 2 (i.e. you don't check if argv[1] is valid). - Kevin
I think that's probably the problem; check whether argc > 2 and exit if it isn't before you try to open the first file. - wizzwizz4
@nicomp The program doesn't have a line 30. That's line 30 inside Microsoft's header files, or something. MSVC isn't very helpful. - wizzwizz4

1 Answers

1
votes

Your program makes all the necessary checks everywhere... except your first fopen. If argc is 1, which it is if you just run your program, then the value you pass to fopen will be NULL, not a pointer to a valid string. (If argc is 0, which is possible, it won't even be NULL and will instead cause Undefined Behaviour.)

To fix this, change:

if(!(source_fp=fopen(argv[1],"wb")))
{
    printf("can't open file\n");
    return 0;
}

to:

if (argc < 2 || !(source_fp = fopen(argv[1], "wb")))
{
    printf("can't open file\n");
    return 0;
}

Just so you know, the error your compiler's giving you is kind of nonsensical. If you have to use Windows, use a decent compiler like Pelles C. It'll tell you what the actual errors are.

Also, by convention, if something's gone wrong we return something other than 0; usually 1.