0

I know this question has been asked, but the answers I looked at didn't really apply to my case. At the end of my program, a bunch of files are opened for writing. I've limited the list to just two for simplicity. The variable dirPath is a command line argument passed in at execution.

Here's what I tried first:

FILE *fid_sensory_output;
FILE *fid_msn_output;

fid_sensory_output = fopen(strcat(dirPath,"sensory_output"), "w");
fid_msn_output = fopen(strcat(dirPath,"msn_output"), "w");

This doesn't work because strcat doesn't return a copy of the concatenated strings, but instead appends the 2nd arg to the 1st. When looking up a work around, I found these recommendations, to use strcpy and strcat together, or use sprintf.

I first tried sprintf but was getting an error saying that I was trying to pass an int in where a char * was expected, even though dirPath is declared as a char *. I also tried passing in a string literal with no luck.

I tried using strcat and strcpy in various ways without any success either. Any suggestions?

skaffman
  • 398,947
  • 96
  • 818
  • 769
aweeeezy
  • 806
  • 1
  • 9
  • 22

3 Answers3

2

The only way:

FILE *fid_sensory_output;
char *string;

string=malloc(strlen(dirpath)+strlen("sensory_output")+1);
strcpy(string,dirpath);
strcat(string,"sensory_output");

fid_sensory_output = fopen(string, "w");
free(string);
Abend
  • 589
  • 4
  • 14
1

You can use snprintf for this task. Every string operation should consider buffer size to avoid buffer overflows.

snprintf returns the number of characters written to buffer (not including the string terminator '\0')

FILE *fid_sensory_output;
FILE *fid_msn_output;
char path[MAX_PATH];

snprintf(path, sizeof(path), "%s/%s", dirPath, "sensory_output");
fid_sensory_output = fopen(path, "w");

snprintf(path, sizeof(path), "%s/%s", dirPath, "msn_output");
fid_msn_output = fopen(path, "w");
denisvm
  • 720
  • 3
  • 11
-1
char temp_dir_path[256];
strcpy(temp_dir_path, dirPath);
fid_sensory_output = fopen(strcat(temp_dir_path, "sensory_output"), "w");
strcpy(temp_dir_path, dirPath);
fid_msn_output = fopen(strcat(temp_dir_path,"msn_output"), "w");
Gabe Sechan
  • 90,003
  • 9
  • 87
  • 127