Reputation: 23
I'm trying to implement this linux command sequence in c : cd /folder/folder; echo 1000 > file;
i tried this code and it works fine :
int fd, len;
char buf[MAX_BUF];
fd = open("/folder/folder" "/file", O_WRONLY);
len = snprintf(buf, sizeof(buf), "%d", 1000);
write(fd, buf, len);
but i want to declare : char * a = some other folder
, If my folder would change ; and use it :
open(a "/file", O_WRONLY);
but then i get error : expected ')' before string
any ideas how to fix it or implement in different way ? Thank you.
Upvotes: 1
Views: 183
Reputation: 4041
You have to use like this.
char a[]="path to file";
And in open function,
open(a,O_WRONLY);
Upvotes: 3
Reputation: 399863
You can only use adjacency to concatenate string literals, not runtime strings.
To do the latter, just use snprintf()
which you already seem to know about!
Something like:
char fn[1024];
const char *a = "/hello/filesystem";
snprintf(fn, sizeof fn, "%s/file", a);
Or, naturally, put the entire valid path in the variable to begin with:
const char *a = "/hello/filesystem/file";
but that's pretty obvious so I assumed you wanted a runtime solution.
Also, you're not "opening a certain directory", you're opening a file that's in a certain directory.
Finally, check that open()
succeeds before relying on the file descriptor to be valid.
Upvotes: 4