NULL not initializing - c

i'm new to C programming but am getting the hang of it. I'm working on a FILE function and the function will never return NULL. This happens even when the file does not exist and is initialized as "r". The code has worked before, but after that it has kept returning TRUE. I have written the code multiple ways but all return as the file being there. I have even changed the file name to make a completely different file but still get same results. Any help would be great. Thanks in advance.
EDIT:
Thanks everyone. I've gotten it to work.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *fp;
fp = fopen("c:\\lest.txt", "w");
if(fp == NULL)
{
printf("File Not Available\n");
exit(0);
}
fclose(fp);
return 0;
}

You need to be checking fp against null, not fopen.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *fp;
fp = fopen("c:\\lest.txt", "r");
if(fp == NULL)
{
printf("File Not Available\n");
exit(0);
}
fclose(fp);
return 0;
}

fp = fopen("c:\\lest.txt", "r");
if(fopen == NULL)
These lines are so wrong. fopen() is a standard function. So the fopen (without parenthesis) will always be non-NULL as it represents the function pointer of fopen().
What you should do is to check the return value of fopen(). Which is in this case fp.
if(fp==NULL){
perror("fopen");
exit(1);
}
Also note,
To print exact error you should use perror() function.
exit(0) will return 0 to OS. Which indicates success. Better use exit(1).

Instead of testing fopen for null, change the conditional to test fp for NULL instead:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE fp*;
fp = fopen("c:\\lest.txt", "r");
if(fp == NULL)
{
printf("File Not Available\n");
exit(0);
}
fclose(fp);
return 0;
}

as u are saying that even if change the file name & then call fp = fopen("c:\lest.txt", "w"); even there is no existing file of name lest.txt, u get fp!=NULL.
it happens because if the specified file is not present then new file with the specified name in the fopen() function is created then it's file pointer is returned so i think u have gotten ur answer.
for more info please see the man page of the function fopen() http://linux.die.net/man/3/fopen

Related

Programm crashing at fgets() in c

when I run my Program, which should read a simple File, it just crashes at the fgets() function. I get no errors in my IDE or from gcc. I know that there are similar Posts, but I couldn't figure out the Problem with them. So here is my code, and thanks for help!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char a[64];
int main() {
FILE* fp;
fopen("Memory.mem", "r");
fgets(a, 64, (FILE*)fp);
printf("%s\n", a);
// the getchar is just that the Program doesn't close it self imeadiatly
getchar();
return 0;
}
//In the Memory.mem file is just "abcdefg"
The problem is when you fopen you don't actually save the returned file pointer.
When you call fgets fp is uninitialized, thus causing undefined behaviour.
You can fix it by instead of doing this:
FILE* fp;
fopen("Memory.mem", "r");
do this:
FILE* fp = fopen("Memory.mem", "r");
Also note that it is good practice to put a check if opening the file was successful.
FILE* fp = fopen("Memory.mem", "r");
if(fp == NULL){
printf("Couldn't open file!\n");
return EXIT_FAILURE;
}
And you should close the file once you are done using it with:
fclose(fp);

C language: reading a .txt file

I'm trying to write a program that reads a text file, using C with Visual Studio.
This is my current code (which doesn't work):
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *filePTR;
char fileRow[100];
filePTR = fopen_s(&filePTR, "text.txt", "r");
// Opens the file
if(filePTR){
while(!feof(filePTR)) {
// Reads file row
fgets(fileRow, 100, filePTR);
// Displays file row
printf("%s \n", fileRow);
}
printf("\nEnd of file.");
}
else {
printf("ERROR! Impossible to read the file.");
}
// Closes the file
fclose(filePTR);
return 0;
}
I'm getting the following warning:
'filePTR' may be '0': this condition does not meet the function specification 'fclose'.
What am I doing wrong? I haven't been programming in C since a while ...
The problems begin long before the fclose. This line is incorrect:
filePTR = fopen_s(&filePTR, "text.txt", "r");
It overwites the file pointer already assigned by passing a pointer as the function argument &filePTR.
The function returns an error status, not the file pointer. Please see the man page:
Return Value Zero if successful; an error code on failure.
Also, please see Why is while ( !feof (file) ) always wrong?
I suggest this:
#include <stdio.h>
#include <stdlib.h>
int main(void) { // correct definition
FILE *filePTR;
char fileRow[100];
if(fopen_s(&filePTR, "text.txt", "r") == 0) {
while(fgets(fileRow, sizeof fileRow, filePTR) != NULL) {
printf("%s", fileRow); // the string already contains a newline
}
fclose(filePTR); // only close if it was opened
printf("\nEnd of file.");
}
else {
printf("ERROR! Impossible to read the file.");
}
return 0;
}
Note that I moved the fclose call up. You can't close a file that you did not open.

File Pointer Not Being Assigned a Value When Using fopen()

I am trying to write a simple C program which will read data from a csv file and perform some calculations on this data.
Unfortunately I have a problem where a file pointer of mine, fptr , is not being assigned a value after calling fopen(). I know this is the case after stepping through VS 2017's debugger. Yet I do not know why this is the case. This is a huge problem and means my program will throw some very nasty exceptions any time I try to read data from the file or close the file.
My code is below:
main.c
#include<stdio.h>
#include <stdlib.h> // For exit() function
#include"constants.h" //For access to all project constants
/***************************************************************************************************************
To keep the terminal from automatically closing
Only useful for debugging/testing purposes
***************************************************************************************************************/
void preventTerminalClosure() {
//flushes the standard input
//(clears the input buffer)
while ((getchar()) != '\n');
printf("\n\nPress the ENTER key to close the terminal...\n");
getchar();
}
/***************************************************************************************************************
Read the given input file
***************************************************************************************************************/
void readInputFile(char fileName[]) {
FILE *fptr;
char output[255];
//open the file
if (fptr = fopen(fileName, "r") != NULL) { //read file if file exists
//fscanf(fptr, "%[^\n]", output);
//printf("Data from the file:\n%s", output);
printf("<--Here-->");
}else {
printf("\nERROR 1: File %s not found\n", fileName);
preventTerminalClosure();
exit(1);
}
fclose(fptr); //close the file
}
/***************************************************************************************************************
* * * Main * * *
***************************************************************************************************************/
void main() {
char testName[MAX_NAME_SIZE];
printf("Hello World!\n");
printf("Please enter your name: ");
scanf("%s", testName);
printf("It's nice to meet you %s!", testName);
readInputFile("dummy.txt");
preventTerminalClosure(); //Debug only
}
I have made sure that my fake file does indeed exist and is located in the correct location. Otherwise my code would hit the else block inside of readInputFile(). That is something I have thoroughly tested.
There is clearly something basic that I am missing which explains this pointer behavior; but what that is, I am not sure. Any help would be appreciated! :)
Use parenthesis to enforce order, so that fptr is compared against NULL after it has been assigned value returned by fopen:
FILE *fptr;
char output[255];
//open the file
if ( (fptr = fopen(fileName, "r")) != NULL)

the function fgetc is not working properly

i'm testing the fgetc() function but it doesn't work properly (i have used this function befor so i know how it works)
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *file = NULL;
int n;
file = fopen("test.txt", "w+");
if(file != NULL)
{
fputs("ab", file);
printf("%c", fgetc(file));
}
else
{
printf("error");
}
return 0;
}
the output should be "a" but it's somthing else
The file is opened for both writing and reading but you need to fseek to the correct place in the file (here, the beginning). In particular, when switching between writing and reading you need to fseek or fflush.
When the "r+", "w+", or "a+" access type is specified, both reading
and writing are enabled (the file is said to be open for "update").
However, when you switch from reading to writing, the input operation
must encounter an EOF marker. If there is no EOF, you must use an
intervening call to a file positioning function. The file positioning
functions are fsetpos, fseek, and rewind. When you switch from writing
to reading, you must use an intervening call to either fflush or to a
file positioning function.
In any case, after writing to the file, the file pointer is in the wrong place to read what was just written.
So the code becomes
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *file = NULL;
file = fopen("test.txt", "w+");
if(file != NULL) {
fputs("ab", file);
fseek(file, 0, SEEK_SET);
printf("%c", fgetc(file));
fclose(file);
}
else {
printf("error");
}
return 0;
}
And if you want to continue writing to the file, you must fseek to its end.
Your error is that you are trying to read a file that has been opened for writting. You should write inside it, then close the file and reopen it for reading. This code will show what I am telling:
#include<stdio.h>
#include<stdlib.h>
int main()
{
FILE *fileRead, *fileWrite = NULL;
int n;
fileWrite = fopen("test.txt", "w+");
if(fileWrite != NULL)
{
fputs("ab", fileWrite);
fclose(fileWrite);
}
else
{
printf("error");
}
// Open again the file for read
fileRead = fopen("test.txt", "r");
printf("%c", fgetc(fileRead));
fclose(fileWrite);
// End function
return 0;
}

Opening file to write to in the same directory as the program, however, file cannot be found

I am trying to write to a file, however, the file pointer is always pointing to NULL as if the file does not exist. The file is in the same directory as the input file, which is found and written to. Any ideas as to why this is happening?
FILE *vmoutput = NULL;
fopen("vmoutput.txt", "w");
// if file could not be opened return error
if(vmoutput == NULL)
{
printf("FILE COULD NOT BE FOUND\n");
return 1;
}
How about you fix your code to:
store and check fopen's return value
report the actual error
?
#include <stdio.h>
#include <string.h>
#include <errno.h>
...
FILE *vmoutput = fopen("vmoutput.txt", "w");
if (vmoutput == NULL) {
fprintf(stderr, "Can't open %s: %s\n", "vmoutput.txt", strerror(errno));
return 1;
}
Right now your code always sets vmoutput to NULL.
Upon successful completion fopen() return
a
FILE pointer. Otherwise, NULL is returned and errno is set to indicate
the error.
So you have to assign the value returned from fopen() to your variable like this. You should also indent your code well.
#include <stdio.h>
int main(){
FILE *vmoutput = NULL;
vmoutput =fopen("vmoutput.txt", "w");
// if file could not be opened return error
if(vmoutput == NULL)
{
perror("Unable to open file\n");
return 1;
}
return 0;
}

Resources