简体   繁体   中英

Why do I receive crash report with argv in this example?

TL;DR

• 1. Why that code giving crash error as it start?

• 2. What argv[] do? Is it receive your cmd input? And how it differentiate from argv 1,2,3...so on?

• 3. Output not showing what is expected when I change argv[1] with VSF.txt

The following code gives an error:

File: minkernel\crts\ucrt\src\appcrt\stdio\fopen.cpp
Line: 30
Expression file_name != null_ptr

错误图片

The idea is to print every file line with the respective number. I don't fully understand files yet and I believing argv[1] is what you write at your compiler prompt, is that right? How it differentiate with argv 1,2,3...and so on?

If I change argv[1] with VSF.txt (the file name) it shows strange chars (not what is inside VSF.txt )

VSF.txt图片

cmd输出

The output is showing everything with just one line, no space and line variable not incrementing; why it isn't printing the content of VSF.txt ?

#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

main(int argc, char *argv[])
{
    FILE *file = stdout;
    int lines = 1, start = 1;
    char ch;

    if ((file = fopen(argv[1], "r")) == NULL)
    {
        printf("Impossivel de abrir o arquivo :%s", argv[1]);
        exit(0);
    }
    while (ch = fgetc(file) != EOF)
    {
        if (ch == '\n')
        {
            lines++;
            start = 1;
        }
        else if (start == 1)
        {
            printf("%d: ",lines);
            putchar(ch);
            start = 0;
        }
        putchar(ch);
    }
    fclose(file);
}

The problem with the strange output is here:

while (ch = fgetc(file) != EOF)

The inequality operator != has higher precedence than the assignment operator = . So the expression above is the same as:

while (ch = (fgetc(file) != EOF))

This assigns ch a boolean value, either 0 or 1. That's why you get the output you get. Put parenthesis in the proper place:

while ((ch = (fgetc(file)) != EOF)

As for the crash, that is happening because you're not telling the program the name of the file you want to open when you run it. If you run it from a command prompt, do so like this:

archives VSF.txt

If you run it from inside Visual Studio, go to the project settings, and under Debugging set Command Arguments to VSF.txt.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM