1

Sorry for asking a basic question but how would I do the following to get the pid to be part of the file name like this:

int pid;
int fOUT;enter code here
pid=getpid();
// TRYING TO EVALUATE HERE
char* filename=printf("hello-world-%i.txt", pid); # obviously wrong 
//char* filename="here.txt";
fOUT= open (filename, O_RDWR | O_CREAT | O_SYNC);

thx for any help

timpone
  • 19,235
  • 36
  • 121
  • 211

2 Answers2

3

You can use snprintf and allocated buffer for this:

#include <limits.h>

// ...

char filename[PATH_MAX];
snprintf(filename, sizeof(filename), "hello-world-%d.txt", pid);

About PATH-MAX: Where is PATH_MAX defined in Linux? and this link.

Community
  • 1
  • 1
Nemanja Boric
  • 21,627
  • 6
  • 67
  • 91
  • @timpone See the edit - it should be the `maximum number of bytes in a pathname, including the terminating null character.` Also, see this link, if it is important for you: http://www.gnu.org/software/hurd/hurd/porting/guidelines.html. – Nemanja Boric Nov 25 '13 at 20:29
  • 1
    great, thx for answer. works like a charm; need to wait a few – timpone Nov 25 '13 at 20:32
  • @timpone - _what should MAX_PATH be?_ typically defined as 260. Always safer to use macro rather than hard-coding a value though. – ryyker Nov 25 '13 at 20:45
2

You are looking for snprintf, or perhaps more conveniently (but less portably) asprintf.

zwol
  • 135,547
  • 38
  • 252
  • 361