Espen
Espen

Reputation: 147

Create a textfile where filename is based on the value in one or two arrays

In a C-program I am trying to create a textfile where the file name should be based on the input to one or two char arrays in a structure.

At the moment I query the filename like this:

printf("Type a filename:");
scanf("%s", &filename);
strcat(&filename, ".txt");
pFile=fopen(filename,"a");

…but let's say my input to my char array is John , how could this input be used to create the filename John.txt ?

..or even better: combine a name from two char arrays:

fgets(pIndex->name, 20, stdin);  //lets say input here is John
fgets(pIndex->country, 20, stdin);  //...and input here is England

to generate a filename like JohnEngland.txt

Thanks a lot !

-Espen

Upvotes: 0

Views: 153

Answers (3)

Weather Vane
Weather Vane

Reputation: 34585

You can generate a filename like JohnEngland.txt with this

char filename[45];
sprintf (filename, "%s%s.txt", pIndex->name, pIndex->country);

Upvotes: 2

hetepeperfan
hetepeperfan

Reputation: 4421

You can use the function strcat and friends to concatenate multiple strings. I prefer strncat over strcat especially with user input, to prevent bufferoverflows. also don't use "%s" in the scanf, because that allows the user to insert any length of string which in turn also leads to buffer overflows.

#include <string.h>

const char* suffix = ".txt";
char filename[1024];
char* output = NULL;

scanf("%50s", filename); // Don't use %s because that could lead to a buffer overflow and is therfor insecure.
output = strncat(filename, suffix, 1024);

after the strncat filename will have the suffix appended. check man strcat or your local resource for other issues involving strncat.

Upvotes: 1

Iharob Al Asimi
Iharob Al Asimi

Reputation: 53016

To prevent overflow do

snprintf(filename, sizeof(filename), "%s%s.txt", pIndex->name, pIndex->country);

or the MS Windows variant

sprintf_s(filename, sizeof(filename), "%s%s.txt", pIndex->name, pIndex->country);

Upvotes: 1

Related Questions