Search code examples
cparsingc-preprocessorargvargc

How do i open a file through a string in C


So im trying to use argc and argv to make a string and open a file through what I put into the command line but im getting:

A3.c:14:30: error: expected ‘;’, ‘,’ or ‘)’ before string constant
FILE *fopen(const char * "levelFile.txt", const char * "r+");

Also how do i go about parsing the file after this.

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

int main(int argc, char *argv[])
{
  int i;

  for(i = 0; i < argc; i++)
  {
      printf("argv[%d] = %s\n", i, argv[i]);
  }

  printf("%s", argv[1]);
  FILE *fopen(const char * "%s", const char * "r+", argv[1]);
}

Solution

  • FILE *fopen(const char * "%s", const char * "r+", argv[1]); // Wrong - you mixed up prototype with function call.

    Should be:

      FILE *pFile = fopen(argv[1], "r+");  // declare a file pointer and initialize it to open the file with desired mode.
      if( NULL == pFile )  // check if file is opened ok.
      {
        fprintf(stderr, "Failed to open file");
      }