Question

The issue I am having is simply opening a file which has a number based on an input. Example included:

int main(int argc, char *argv[])
{
  int argument = atoi(argv[1]);
  FILE *fp;
  fp = fopen("/folder/item'argument'file", "r");
  //do stuff to the file
}

Example passing 4 will open the file called "item4file" for use

How would I address this?

Sincere thanks for any and all help

Was it helpful?

Solution

int argument = atoi(argv[1]);  
FILE *fp;
char address[50]; // choose the size that suits your needs
sprintf (address, "/folder/item%dfile", argument);
fp = fopen(address, "r");

As you can read from the reference, a terminating null character is automatically appended to the string.

If you want to avoid buffer overflows, however, you should use snprintf (which is shown in the same reference page as above), declaring the maximum size of the buffer so that the input doesn't overflow it.

int argument = atoi(argv[1]);  
FILE *fp;
char address[50]; // choose the size that suits your needs
snprintf (address, 49, "/folder/item%dfile", argument); // 49 since we need one index for our null terminating character

OTHER TIPS

use sprintf() as

char filename[50]
strcpy(filename,"/folder/item");
sprintf(str,"%s",argv[1]);
strcat(filename,str);
strcat(filename,"file");
fp=fopen(filename,"r");

Use snprintf to convert an integer into a string suitable for use in a file pathname.

#include <stdio.h>
#include <limits.h>

int main(int argc, char *argv[])
{
  int argument = atoi(argv[1]);
  char pathname[PATH_MAX];
  FILE *fp;

  snprintf(pathname, PATH_MAX, "/folder/item%dfile", argument);
  fp = fopen(pathname, "r");
  if (fp != NULL) {
    //do stuff to the file
  }
}

Have a look at http://www.cplusplus.com/reference/cstdio/sprintf/. It allows you to print to string buffer.

You can use it like this

char filename[30];
sprintf(filename, "/folder/item%dfile", argv[1]); 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top