Home > Enterprise >  can i store 'mode' in a variable and use it at fopen()
can i store 'mode' in a variable and use it at fopen()

Time:12-01

char mode;

printf("---------------------------------------")
scanf(" %c", mode);
FILE * fpointer = fopen("kkkkkkkk.txt", mode);`

I tried but no result. compiler doesn't gives me error but not getting the program run completely.

CodePudding user response:

Welcome to Stack Overflow.

The second argument of fopen(3) should be a of type const char * (essentially, a string). However, you've used a single char which will not work. Also, I don't think you've initialised it. Here's a working example.

#include <stdio.h>

int main(void) {
  char mode[5];
  scanf("%s", mode);
  printf("Received mode is '%s'\n", mode);
  FILE *fp = fopen("sample.txt", mode);
  if (fp == NULL) {
    perror("Couldn't open file ");
  } else {
    printf("Done! Closing\n");
    fclose(fp);
  }
}

Here are two runs to indicate what's going on.

ن ./sample
r
Received mode is 'r'
Couldn't open file : No such file or directory

Opening it in "r" mode here. Since sample.txt doesn't exist, we get an error.

ن ./sample
w
Received mode is 'w'
Done! Closing

ن ./sample
r
Received mode is 'r'
Done! Closing

The first time, it opens in "w" mode and creates it. The next time, "r" will work since the sample.txt file exists.

CodePudding user response:

The mode argument needs to be a string, not a single character, since you have modes like r , wb, wbx , etc. So your mode variable needs to be an array of char that’s at least 5 elements wide:

char mode[5]; // up to 4 characters plus string terminator

You’d then use the %s conversion specifier with scanf (or, preferably, fgets) to read the input string:

#define MODE_LEN       4
#define FILENAME_LEN 255

FILE *fp = NULL;
char filename[FILENAME_LEN 1] = {0}; //  1 for string terminator
char mode[MODE_LEN 1] = {0};         // initialize to all 0

printf( "Gimme a file name: " );
if ( !fgets( filename, sizeof filename, stdin ) )
{
  // input error, bail out here
  exit( 0 );
}

printf( "Gimme the fopen mode: " );
if ( !fgets( mode, sizeof mode, stdin ) )
{
  // input error, bail out here
  exit( 0 );
}

fp = fopen( filename, mode );
if ( !fp )
{
  fprintf( stderr, "Could not open %s with mode %s\n", 
    filename, mode );
  exit( 0 );
}

// read/write fp here

fclose( fp );
  •  Tags:  
  • c
  • Related