C ошибка file null

В чём может заключаться ошибка при открытии файла.Путь к файлу прописал и проверил несколько раз:

FILE* fp;
    char words[MAX] = { 0 };
    fp = fopen("C:\\Users\\Elvin\\Desktop\\lol.txt", "a+");
    if (fp == NULL);
    {
        fprintf(stdout, "unable to open up the file");
        exit(EXIT_FAILURE);
    }

указатель почему-то всегда равен NULL.Почему возникают ошибки подобного рода ?

задан 1 авг 2018 в 17:47

Elvin's user avatar

10

Попробуйте выполнить такой фрагмент — что будет выведено?

FILE* fp;
char words[MAX] = { 0 };
fp = fopen("C:\\Users\\Elvin\\Desktop\\lol.txt", "a+");
if (fp == NULL)
{
    perror("File opening failed");
    exit(EXIT_FAILURE);
}

P.S. Надеюсь, точка с запятой после (fp == NULL) у вас — опечатка?
P.P.S. В любом случае — чтобы узнать подробнее об ошибке при открытии файла, можно использовать значение переменной errno, или, например, функцию perror, которая выводит соответствующее «человеческое» сообщение.

ответ дан 1 авг 2018 в 17:52

Harry's user avatar

HarryHarry

217k15 золотых знаков117 серебряных знаков229 бронзовых знаков

4

На вопрос автора как включить предупреждения в MSVC покажу картинку:

введите сюда описание изображения

ответ дан 3 авг 2018 в 7:36

NewView's user avatar

NewViewNewView

2,30810 серебряных знаков20 бронзовых знаков

I am trying to read a file which is located at the same source as my .c code. I tried this little sketch and same problem. What could be wrong?
File’s extension and name are just the same.

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

int main (){
    char caracter;
    FILE *ARCHIVO;
    ARCHIVO=fopen("prueba.txt", "r");
    if (ARCHIVO==NULL){
        printf("Error·");
    }else{
        while (feof(ARCHIVO)==0){
            caracter=fgetc(ARCHIVO);
            printf("%c", caracter);
        }
    }
    fclose(ARCHIVO);
    return 0;
}

I will be very thankful if someone could help me.
Regards.

asked Dec 8, 2016 at 18:42

Juanjo Daza's user avatar

5

Your file doesn’t have the read permission thats why it is giving the error while.

Try the following :

chmod a+r prueba.txt 

This will fix the problem. Hope so !!!

answered Dec 8, 2016 at 20:33

Sohil Omer's user avatar

Sohil OmerSohil Omer

1,1717 silver badges14 bronze badges

  • Remove From My Forums
  • Question

  • My PC is a 64-bit HP Pavilion model dv7-6b55dx running Windows 7 Home Premium w/ SP1.  
    This PC will not support MS Visual Studio C++ 2008 Express. 
    I does support MS Visual Studio C++2010 Express, which I have installed and have successfully used to produce win32 console apps that run 
    both on this PC an on 32-bit PCs running Windows XP.  
    Recently I tried to create a win32 Windows GUI app using  MS Visual Studio C++2010 Express.  
    I started by editing the files <appname>,cpp, <appname>.cpp, <appname>.h and stdafx.h autogenerated by VS.  
    I encountered the following issue running the debug version of my app:

    Upon executing the following code, the value of fin returned by fopen is NULL.

    #include «stdafx.h»  // which contains the statement #include <stdio.h>
       .
       .
    {
      FILE *fin;
         .
         .
      fin = fopen(«Data.txt»,»r»)    // where file Data.txt exists in the debug working directory.  
      if (fin==NULL)
      {
        …
      }
    }

    None of the answers to similar problems in the forum address my issue. 
    I.e., the file exists and is not opened by any other app.   
    I verified (via a hex editor) that the contents of the input file are indeed pure byte-ordered ASCII w/o any file header.  

    VS Watch window indicates the return value of fin is 0x00000000.  Interestingly, however, the app does not enter the if (fin==NULL) block which follows the fopen statement.

    How do I rectify this problem?

    The Bard


    rwh

Answers

  • VS Watch window indicates the return value of fin is 0x00000000.  Interestingly, however, the app does not enter the if (fin==NULL) block which follows the fopen statement.

    >VS Watch window indicates the return value of fin is 0x00000000.

    How and where are you checking it? Did you do a breakpoint?

    >Interestingly, however, the app does not enter the
    >if (fin==NULL) block which follows the fopen statement.

    Then the fopen succeeded and fin is *not* NULL.

    I suspect you are misreading the Watch window data.
    You may be seeing the value of one of the data members
    in the FILE struct which happens to be 0x00000000,
    such as _ptr. For example:

    -		fin	0x10311448 {_ptr=0x00000000 <Bad Ptr> _cnt=0 _base=0x00000000 <Bad Ptr> ...}	_iobuf *
    +		_ptr	0x00000000 <Bad Ptr>	char *
    		_cnt	0	int
    +		_base	0x00000000 <Bad Ptr>	char *
    		_flag	1	int
    		_file	3	int
    		_charbuf	0	int
    		_bufsiz	0	int
    
    

    In this Autos window output after a breakpoint, the value
    0x10311448 is what is in fin. The other values are the
    contents of the FILE struct and you should not be
    concerned with them. They reflect status info about
    the file which is used by the RTL file handling code.

    — Wayne

    • Marked as answer by

      Tuesday, January 8, 2013 4:00 AM

  • Hi,

    When fopen in CRT fails it will set the error code in  global errno.
    could you please check what error code it contains.

    As specified you can check the current directory also and make sure its correct

    As CRT code is come along with visual studio you can debug and find out the issue from code.
    In my system the code is located in following location
    C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\crt\src)

    thanks,
    Bhash

    • Marked as answer by
      Elegentin Xie
      Tuesday, January 8, 2013 4:00 AM

  • Home
  • Forum
  • General Programming Boards
  • C Programming
  • FILE pointer null checking problem

  1. 01-06-2004


    #1

    techrolla is offline


    Registered User


    FILE pointer null checking problem

    I am having a problem checking whether a file is null or not:

    Code:

    FILE *fp;
    if((fp = fopen("test.txt", "w") == NULL)

    This should work, but microsoft throws a debug assertion failed, I don’t understand, any ideas? This is on xp.


  2. 01-06-2004


    #2

    Salem is offline


    and the hat of int overfl

    Salem's Avatar


    Yeah, your () are in the wrong place

    fp = fopen(«test.txt», «w») == NULL
    is the same as
    fp = ( fopen(«test.txt», «w») == NULL )


  3. 01-06-2004


    #3

    Prelude is offline


    Code Goddess

    Prelude's Avatar


    >Yeah, your () are in the wrong place
    More like mismatched. The OP is missing one:

    Code:

    if((fp = fopen("test.txt", "w")) == NULL)

    My best code is written with the delete key.


  4. 01-06-2004


    #4

    techrolla is offline


    Registered User


    This missing ) was just a copy paste error. I still get the problem. Its a runtime error, here is most of the text from the microsoft visual c++ error dialog:

    Debug assertion error!

    …. some file info here…
    file: fgets.c
    line: 59

    Expression: string != NULL

    *************
    this is when I run the program with a text file to load. If you want me to post the main functions used, I can. Thanks.

    EDIT: Actually, the error, after some commenting out, seems to be coming from this function:

    Code:

    struct editor_stuct {
    	char buffer[BUFSIZE];
    } *editor;
    
    
    int openFile(FILE *fp)
    {
    	if(fp != NULL)
    	{
    		while(fgets(editor->buffer, BUFSIZE - 1, fp)) 
    		{ 
    			printf("%s", editor->buffer); 
    		}
    		return FILE_SUCCESS;
    	}
    
    	return FILE_ERROR;
    }

    with or without the if(fp != NULL) this error is thrown

    Last edited by techrolla; 01-06-2004 at 04:05 PM.

    you make me rery ascared


  5. 01-06-2004


    #5

    Dave_Sinkula is offline


    Just Lurking

    Dave_Sinkula's Avatar


    Code:

    struct editor_stuct {
    	char buffer[BUFSIZE];
    } *editor;

    Does the pointer ‘editor’ point to memory you own?

    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*


  6. 01-06-2004


    #6

    Prelude is offline


    Code Goddess

    Prelude's Avatar


    >while(fgets(editor->buffer, BUFSIZE — 1, fp))
    Is editor pointing to a valid editor_struct? Also, you don’t need to pass BUFSIZE — 1 (if you were doing it with the nul terminator in mind), fgets handles that kind of thing for you.

    My best code is written with the delete key.


  7. 01-06-2004


    #7

    Salem is offline


    and the hat of int overfl

    Salem's Avatar


    Ah, so this is one of those «post one line at a time» jobs where we get to guess at each stage all the possible things you could have screwed up

    It seems that this time you’ve failed to allocate any memory for your editor pointer.


  8. 01-06-2004


    #8

    quzah is offline


    ATH0

    quzah's Avatar


    Code:

    struct editor_stuct {
    	char buffer[BUFSIZE];
    } *editor;

    You do realize that ‘editor’ is just a pointer, and doesn’t actually point at anything, right?

    [edit] Curses. Foiled again. [/edit]

    Quzah.

    Hope is the first step on the road to disappointment.


  9. 01-06-2004


    #9

    techrolla is offline


    Registered User


    Okay, I guess the problem is the editor pointer. I made buffer a local variable and it worked, but how could I make it so I owned it? Would I use memalloc? I have to admit, this is my first attempt with c i/o or c in general.


  10. 01-06-2004


    #10

    Salem is offline


    and the hat of int overfl

    Salem's Avatar


    Well your best bet is to leave all those * and -> operators out of it for the moment and go with memory which the compiler allocates for you.

    So

    Code:

    struct editor_stuct {
    	char buffer[BUFSIZE];
    } editor;
    
    
    int openFile(FILE *fp)
    {
    	if(fp != NULL)
    	{
    		while(fgets(editor.buffer, BUFSIZE - 1, fp)) 
    		{ 
    			printf("%s", editor.buffer); 
    		}
    		return FILE_SUCCESS;
    	}
    
    	return FILE_ERROR;
    }

    Making something which works with fixed allocations of memory is a lot easier, and the change to dynamic allocation later on is fairly trivial.


  11. 01-06-2004


    #11

    techrolla is offline


    Registered User


    thanks, but what if I want to use a pointer for editor? malloc()? something like this:
    *editor = (editor_struct *)malloc(sizeof(editor_struct)); that doesnt work I know, but its something I guess.

    Okay, Ive edited this post like 5 times and I finally got it, please ignore the above…

    Code:

    	editor_struct *struce;
    	struce = (editor_struct *)malloc(sizeof(editor_struct));

    is it right to use the sizeof for that?

    Last edited by techrolla; 01-06-2004 at 04:30 PM.

    you make me rery ascared


  12. 01-06-2004


    #12

    Salem is offline


    and the hat of int overfl

    Salem's Avatar


    In C, we don’t cast the return result of malloc (see the FAQ, many previous posts)

    struce = malloc(sizeof(editor_struct));

    Whilst your use of sizeof is correct, there is a better way which is a bit less effort, and is slightly more maintainable in the long run

    struce = malloc( sizeof *struce );
    If the type of the pointer changes, the malloc call automatically adapts without you having to change any code.


  13. 01-06-2004


    #13

    techrolla is offline


    Registered User



Popular pages

  • Exactly how to get started with C++ (or C) today
  • C Tutorial
  • C++ Tutorial
  • 5 ways you can learn to program faster
  • The 5 Most Common Problems New Programmers Face
  • How to set up a compiler
  • 8 Common programming Mistakes
  • What is C++11?
  • Creating a game, from start to finish

Recent additions subscribe to a feed

  • How to create a shared library on Linux with GCC — December 30, 2011
  • Enum classes and nullptr in C++11 — November 27, 2011
  • Learn about The Hash Table — November 20, 2011
  • Rvalue References and Move Semantics in C++11 — November 13, 2011
  • C and C++ for Java Programmers — November 5, 2011
  • A Gentle Introduction to C++ IO Streams — October 10, 2011

Similar Threads

  1. Replies: 12

    Last Post: 05-03-2009, 11:29 AM

  2. Replies: 14

    Last Post: 05-21-2008, 11:16 AM

  3. Dikumud

    By maxorator in forum C++ Programming

    Replies: 1

    Last Post: 10-01-2005, 06:39 AM

  4. Replies: 6

    Last Post: 02-19-2005, 12:25 PM

  5. Replies: 18

    Last Post: 06-18-2002, 01:27 PM

Overview

We don’t have any direct support of error handling in C language but there are some functional methods used to handle errors while performing file operations:
perror(), strerror(), ferror(), feof(), clearerr() and Exit status.
The errors are very common when we try to read a file that doesn’t even exist or when we try to use a file that has not been opened. To identify the type of error, we can refer to errno. It is a global variable, automatically initialized with a numeric value whenever we call a function.

Error Handling in C Language

Ever wondered while performing file operations what if we try to open a file for reading data that doesn’t even exist? Obviously, we will get some errors and these errors are very common in practical life.

Example of Error handling in C

We all must have encountered so many common errors either while reading data from a file or while writing data to a file. These errors arise usually:

  • When we try to read from a file that doesn’t exist.
  • When we use a file that has not been opened.
  • When we try to write data to a file that has been opened only for reading mode.

In this C program, we are trying to open test.txt file in reading mode to read data from the file. Considering in case if such file doesn’t exists, we have taken care of error handling using some methods defined in errno.h header file. If such file doesn’t exists, error message will be printed and otherwise, it will read and print the data from the file.

We will study errno values and error handling methods in the later course of the article.


Here, we have declared a file pointer and using it, we have opened «test.txt» file. If fp pointer is NULL, that means the file doesn’t exists and we print error message.

Output:


Assuming the data present in the file is integer 100 and therefore, in presence of file we have printed the file data. We have also taken care of error handling and thus, in absence of file we are printing error message.

What is Errno?

When we call a function in C language, a variable is automatically initialized with a numeric value and we can use that to identify the type of error if encountered while writing the code. This variable is called errno value. It is a global variable that is defined in errno.h header file.
There are a total of 13 errno values in C language and each errno has an error message associated with it. These are illustrated below:
(Different types of possible error messages):

Errno Value Error Message
1 Operation not permitted
2 No such file or directory
3 No such process
4 Interrupted system call
5 I/O error
6 No such device or address
7 Argument list too long
8 Exec format error
9 Bad file number
10 No child processes
11 Try again
12 Out of memory
13 Permission denied

1. Operation not permitted: Sometimes while performing operations of file handling in C, we try to read from a file or change permissions of a file by accessing it. If we don’t have ownership rights or system rights to access a file, then we get this particular error message.

2. No such file or directory: This error message occurs whenever we try to access a file or directory that doesn’t exists. It also occurs when we specify wrong file destination path.

3. No such process: When we perform some operations that are not supported during file handling in C, it gives no such process error.

4. Interrupted System call: If we try to read user’s input and if there is no input present, then the system calling process will not return any value and will be blocked forever. This results in interrupted system calls.

5. I/O error: I/O stands for input/output errors that occur when system is not able to perform basic operations like reading from a file or copying data from one file to another.

6. No such device or address: When we specify incorrect device path or address while opening or accessing them, this error occurs.

For example: If we are trying to access a device driver using its path but in actual, it has been removed from the system.

7. Argument list too long: This error generally occurs when we work with large number of files.

For example: If we need to get count of no. of files in a directory (consisting of large number of files) that starts with string — «Scaler», then due to limited buffer space it will show an error message — «Argument list too long» as no. of files in that directory will be equal to the arguments list.

8. Exec format error: This error occurs when we try to execute a file that is not executable or has an invalid executable-file format.

9. Bad file number: This error occurs generally when we try to write to a file which is opened for read-only purpose.

10. No child process: If a process has no further sub-process or child process, then the code returns -1 value and we get no child process error message.

11. Try again: An attempt to create a process fails, when there are no more process slots or not enough memory available. We then get try again error.

12. Out of memory: This error occurs when there is not enough memory available to execute a process.

13. Permission denied: This error occurs when we try to read from a file that is not opened. It suggests that an attempt was made to access a file in a way that is incompatible with the file’s attributes.

Methods of Error Handling in C

If we do not keep a check on errors, then it may result in either termination for the program or it may result in giving incorrect outputs. These errors can also change the logical flow of the code. Therefore, it is very important for the programmers to keep an eye on the unchecked errors if present in the code.
Below are some funtional methods of error handling in C Library that are helpful while performing file operations:

1. perror()

  • perror() function stands for print error and when called by the user, it displays a message describing about the most recent error that occured in the code.
  • perror() function is contained in stdio.h header file.

Syntax:


Here, str1 is a string containing a custom message that is to be printed before the error message itself.

  • User-defined message is printed firstly, followed by a colon and then the error message is printed.
  • We can call perror() function even if no error has encountered and in that case, it will display ‘No Error’ message.

C Program to illustrate the use of perror() function:
In this program with the help of perror() function, we are displaying an error message when there is no file available naming «test.txt».


We have declared a file pointer ‘fp’ and using it, we are trying to open «test.txt» file in read only mode. If file doesn’t exists i.e. fp is NULL, we call perror() function to print the error message.

Output:


Here, string — «Message from perror» is user-defined parameter passed in the function that is printed before the actual error message.

2. strerror()

  • strerror() function is contained in string.h header file.
  • It takes ‘errno’ as an argument and returns the string error message of currently passed errno.

Syntax:


Here, errnum is the error number (errno value) using which, respective error message will be displayed accordingly.

C Program to illustrate the use of strerror() function:
In this program with the help of strerror() function, we are displaying an error message using errno value when there is no file available naming «test.txt».


After opening the file in read only mode using file pointer fp, we check that if fp is NULL i.e. the file doesn’t exists and then we pass errno as parameter in strerror() function that will print respective error message.

Output:


As the file doesn’t exists, we have printed errno-2 error message i.e. No such file or directory.

3. ferror()

  • ferror() function is contained in stdio.h header file.
  • This function basically checks for error in the file stream. It returns zero value if there is no error or else, it returns a positive non-zero value in case of error.
  • File pointer stream is passed as an argument to the function. It will check for the error until the file is closed or we call clearerr() function.
  • To identify the type of error, we can further use perror() function.

Syntax:


C Program to illustrate the use of ferror() function:
In this program, we are trying to read data from the file but has opened the file in the wrong access mode i.e, writing mode. Now, ferror() function will detect this error in the file stream and using perror() function, we will display the error message.


Output:


Here, we are printing error messages both user-defined and from perror() function as well.

4. feof()

  • feof() function is contained in stdio.h header file.
  • This function tests for end-of-file (eof indicator) for the file pointer stream passed as an argument to the function.
  • On detecting that the end-of-file indicator associated with the file stream is set, it returns a non-zero positive value or else, zero is returned.

Syntax:


Here, file pointer stream is passed as an argument and on detecting the end-of-file, this function will return a non-zero positive value.

C Program to illustrate the use of feof() function:
In this program, we are trying to read data from the file and to avoid printing the garbage value characters, we are using feof() function. On detecting the end-of-file, it will return a non-zero value and hence, breaks the loop.


Output:
Assuming there’s some data present in the «test.txt» file, it will read and print:


In absence of feof() function, it will further print the garbage value characters.

5. clearerr()

  • clearerr() function is contained in stdio.h header file.
  • This function clears the end-of-file and the error indicators from the file stream.
  • Error indicators are not automatically cleared and they continue to return the errors until clearerr() function is called.

Syntax:


C Program to illustrate the use of clearerr() function:
In this program, we are trying to read data from the file but has opened the file in the wrong access mode i.e, writing mode. Now, we will clear the error indicators using clearerr() function from the file stream and hence, ferror() couldn’t then detect that error again.


After opening the file in writing mode, we are trying to read data from it using fgetc() and therefore, using ferror() function we can detect the error. After using clearerr() function, it will remove the error in the file pointer stream and further, we won’t get any error on checking through ferror() function.

Output:


In absence of clearerr() function, output will be:


6. Exit Status

  • The macros of exit status() functional method are defined in stdlib.h header file. They are used to inform calling function about the error.
  • There are two constant exit status values available for the exit() function: EXIT_STATUS and EXIT_FAILURE.
  • When program code comes out after a successful operation, then EXIT_SUCCESS is used to show successful exit. Its value is defined as 0.
  • We use EXIT_FAILURE in case of failures or abrupt termination of the program. Its value is defined as -1.

Syntax:


C Program to illustrate the use of Exit Status function:
In this program, we are illustrating the use of two exit function constant values: EXIT_SUCCESS and EXIT_FAILURE depending upon how the program code is terminated.


After opening a file using file pointer fp, if it doesn’t exists then we will print the error messages and exit from the function (EXIT_FAILURE). If file exists, then we will exit from the program by executing else condition here (EXIT_SUCCESS).
Output:
In case, if «test.txt» file doesn’t exists: exit(EXIT_FAILURE)


7. Division by zero

  • If we divide a number by zero, C programming language will give warnings and also give runtime error.
  • To avoid such an undefined behaviour, there is no construct or method in C.
  • To avoid such situations, we can check the value of divisor before using it for division purposes. This can be done using if-else conditions and whenever we encounter such a situation, we can simply print error message.

C Program to illustrate the error of Division by zero:
In this program, we are keeping a check if in case we get zero number value for division that can produce errors and can also abruptly terminate the program.


Here, we have passed the value x in division function. Using if condition we check if it is 0, then we can’t perform division using it. Using else condition, we divide 10 by x and then print the resultant value.
Output:


Conclusion

  • In C language when we call a function, a variable called errno is assigned with a numeric value and we can use that to identify the type of error if encountered while writing the code.
  • When we perform operations of file handling in C, there are some common errors that we may encounter such as reading a file that doesn’t even exists or using a file that has not been opened.
  • To avoid errors while performing file operations, we have some helpful functional methods for error handling in C language:
    perror(), strerror(), ferror(), feof(), clearerr() and Exit status.

Понравилась статья? Поделить с друзьями:
  • Bulletstorm full clip edition ошибка при запуске
  • Bulletsharp dll ошибка 3ds max
  • Bulk insert игнорировать ошибки
  • Bulb failure right turn si 62 ошибка вольво
  • Building native binary with il2cpp ошибка unity