조욱희
조욱희

Reputation: 3

I don't know why the file won't open

This is my code

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

#define TRUE    1
#define FALSE   0

typedef struct {    
    int M,N;    
    int min,max;    
    int width;    
    int height;    
    unsigned char **pixels;    
}PPMIMG;
    
int fnReadPPM(char* fileNm,PPMIMG* img);

int main(int argc, char ** argv)
{    
    PPMIMG img;        

    if(fnReadPPM(argv[1], &img) != FALSE)
    {    
        return TRUE;    
    }

    return  0;
}

int fnReadPPM(char* fileNm ,PPMIMG* img)
{    
    FILE* fp;    
    fp = fopen("/users/ashton/Downloads/test.txt","rb");
    
    if(fileNm == NULL){    
        fprintf(stderr,"Unable to File ! : %s\n",fileNm);    
        return FALSE;    
    }
    
    fclose(fp);    
    return TRUE;
}

int fnWritePPM(char* fileNm, PPMIMG* img)
{    
    FILE *fp =fopen(fileNm, "w");    
    if(fp == NULL)
    {    
        fprintf(stderr, "Failed to create the file.");    
        return FALSE;    
    }        
    return TRUE;
}

This is the error code:

Unable to File ! : (null)
Program ended with exit code: 0 

Upvotes: 0

Views: 75

Answers (2)

Jabberwocky
Jabberwocky

Reputation: 50912

The problem ist most likely here:

int fnReadPPM(char* fileNm ,PPMIMG* img)
{
    FILE* fp;
    fp = fopen("/users/ashton/Downloads/test.txt","rb"); // you assign fp
    
    if (fileNm == NULL){                                // and here you check for fileNm 
        fprintf(stderr,"Unable to File ! : %s\n",fileNm);
        return FALSE;
    }    
    ...

You want this:

int fnReadPPM(char* fileNm ,PPMIMG* img)
{
    FILE* fp;
    fp = fopen("/users/ashton/Downloads/test.txt","rb");
    
    if (fp == NULL) {
        fprintf(stderr,"Unable to open file %s.\n", fileNm);
        return FALSE;
    }    
    ...

However in the fnWritePPM function you did it right.

Upvotes: 1

fpiette
fpiette

Reputation: 12322

Your wrongly test the fopen return value:

fp = fopen("/users/ashton/Downloads/test.txt","rb");
if (fp == NULL) {    //<===== Was WRONG, you used fileNm instead of fp
    perror("Unable to File");
    return FALSE;
}

Upvotes: 1

Related Questions