In: Computer Science
how to use the filename to be passed to the given function in c ? for example the implementation accepts one command line argument, which is a filename. The filename is a file containing a starting state to be passed to the given function initial() ,which will produce the initial state of the game.
Try this one
int main(int argc, char **argv)
{
if (argc >= 2)
printf("\nGame state is: %s",initial(argv[1]));
return 0;
}
/*******************Test Code*********************/
#include <stdio.h>
#include<stdlib.h>
char* initial(char *filename);
int main(int argc, char **argv)
{
if (argc >= 2)
printf("\nGame state is: %s",initial(argv[1]));
return 0;
}
char* initial(char *filename){
char c[1000];
FILE *fptr;
if ((fptr = fopen(filename, "r")) == NULL)
{
printf("Error! opening file");
// Program exits if file pointer returns NULL.
exit(1);
}
// reads text until newline
fscanf(fptr,"%[^\n]", c);
printf("Data from the file: %s", c);
return c;
fclose(fptr);
}
/*************output***************/
Data from the file: Initial State
Game state is: Initial State
--------------------------------
game.txt is passed as command line parameter having one line
Initial State