简体   繁体   中英

open a certain directory and write to it in c

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.

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.

You have to use like this.

char a[]="path to file";

And in open function,

 open(a,O_WRONLY);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM