audiFanatic
audiFanatic

Reputation: 2504

Modifying C string within a structure pointer

I have code that looks something like this:

typedef struct
{
  char mode;       //e = encrypt, d = decrypt
  char* infile;    //name of infile
  char* outfile;   //name of outfile
  char* password;  //password string
} cipher_t;

int check_files(cipher_t *data)
{
  char temp_path[] = "temp-XXXXX";

  if( /** infile == stdin *//)
  {
    mkstemp(temp_path);
    *data.infile = temp_path;
  }

  //do stuff and return

}

Basically, what I'm trying to do is detect if the user wants to input data from stdin and if so make a temporary file where I can do stuff.

The problem here is that when I set my infile path as shown above, that data is not retained upon exiting the function because it's a local variable. So when I exit the function the temporary file path is lost in the structure. Other than physically copying the string, is there anything else I can do to retain the value?

Upvotes: 0

Views: 156

Answers (2)

alk
alk

Reputation: 70951

Other than physically copying the string, is there anything else I can do to retain the value?

You can declare it static, which would let the "string" live for the whole program's live time.

static char temp_path[] = "temp-XXXXX";

But be aware, that temp_path exists only once, so accessing it by multiple threads might lead to confusion.

Upvotes: 1

wuqiang
wuqiang

Reputation: 644

data->infile = strdup(temp_path);

Upvotes: 2

Related Questions