user3582072
user3582072

Reputation: 67

Runtime error during file operation in C

I am trying to run a C code for file opening and whenever I do that I get a debug assertion failed message.

Here is my code:

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

void main()
{
    FILE *fp1;
    printf("program to demonstrate file operations");
    fp1 = fopen("try1.txt","r");
    if (feof(fp1))
    {
        printf("Yes");
    }
    else 
        printf("No");

    printf("%f",fp1);

    getchar();
}

Upvotes: 0

Views: 421

Answers (5)

Saurabh Meshram
Saurabh Meshram

Reputation: 8436

Before using feof() on fp.
Ensure that fopen() succeeded.

#include <string.h>   /* For strerror() */
#include <errno.h>    /* For errno  */
#include <stdlib.h>   /* For exit() */

fp = fopen ("FaultyFile.txt", "r");

/* Add Error-checking */             
if (NULL == fp)                          
{
    printf ("Error No : [%d]\n", errno);
    printf ("Error Msg: [%s]\n", strerror(errno));
    exit (EXIT_FAILURE);          
}                               

From man(3) fopen:
Return Value: Upon successful fopen() return a FILE pointer. Otherwise, NULL is returned and errno is set to indicate the error.

Upvotes: 0

Saisujithreddy
Saisujithreddy

Reputation: 92

Try to check if the file is opened correctly or not
check if( fp==NULL) using an if condition

if fp==NULL is true, file is not being opened correctly

Upvotes: 0

jjm
jjm

Reputation: 461

Check the return value of

 fp1 = fopen("try1.txt","r");

first. It is fare to check the return values of all standard functions( with proper return values) before proceeding to next step. In this case "fp1" should not be NULL. Please check the file location or check whether file is present in current directory.

Upvotes: 0

Santosh A
Santosh A

Reputation: 5361

Change

if (feof(fp1))

to

if (fp1 && !feof(fp1))

That is check for the return value of fopen(). If unable to open the file it would return NULL.

Edit:

  1. Check if the file is in the same directory as that of exe/binary.
  2. Check whether you have the permission to access the file.

Upvotes: 1

Axalo
Axalo

Reputation: 2953

The Debug assertion failure might be caused by fp1 being null.
This will happen if the file could not have been opened.

Upvotes: 3

Related Questions