简体   繁体   中英

Debug Assertion Failed VS2010

I'm making a very simple program to read in from a text file and print the contents. When the file finishes compiling I keep getting this debug assertion failed message!

I've never seen it before and can't seem to find any solutions.

(It won't let me post an image because my rep isn't high enough!)

The code

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

int main()
{
 FILE *file = fopen("C:\\Users\Kyne\\Desktop\\AdvProgrammingAssignment\\employees.txt", "r");
 char c;

do
{
    c = fgetc(file);
    printf("%c", c);
}
while(c != EOF);

fclose(file);
return 0;

printf("\n\n\n");
system("pause");
}

Step through your code using the debugger to find the line that is causing the debug assertion, and check to see if the file is opened.

In the line

FILE *file = fopen("C:\\Users\Kyne\\Desktop\\AdvProgrammingAssignment\\employees.txt", "r");

it looks like you missed a '\\' before 'Kyne' so it should be

FILE *file = fopen("C:\\Users\\Kyne\\Desktop\\AdvProgrammingAssignment\\employees.txt", "r");

There are other issues like calling return 0; before the end of the main block.

I don't see any checks if file was opened properly. Also, I would check for EOF mark before first read - use while and feof() instead. Finally, these lines:

printf("\n\n\n");
system("pause");

will never get called, as you do return 0 after fclose() - move it [ return 0 ] to the end.

Try this:

int main()
{
    FILE *file = fopen("C:\\Users\\Kyne\\Desktop\\AdvProgrammingAssignment\\employees.txt", "r");

    if(!file)
    {
        printf("File could not be opened!\n");
        return -1;
    }

    while(!feof(file))
    {
        char c = fgetc(file);
        printf("%c", c);
    }

    fclose(file);

    printf("\n\n\n");
    system("pause");

    return 0;
}

Most likely, your error originated in using FILE* set to NULL - you have one slash missing after \\\\Users , so file probably was never opened and fopen() was constantly returning NULL .

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