PDA

View Full Version : open file in c



ferizhandi
May 24th, 2013, 08:20 AM
i want to open a file in c with this function

int open( char *filename, int access, int permission );

but when file exist in other directory , i put path of file in first argument. but can not open the file.

what should i do?!
(i want to use only this function )

Tony Flury
May 24th, 2013, 08:24 AM
Provide your code please and an example of the file name you are trying to open.

Remember that open will not expand things like ~ in your file name - you will need to do this manually, or use other system calls to expand your file name first.

ferizhandi
May 24th, 2013, 08:38 AM
Provide your code please and an example of the file name you are trying to open.



char * path = "/home/testfile";
if(open(path,O_RDONLY,0)<0)
write(1,"file not open",13);

dwhitney67
May 24th, 2013, 01:36 PM
Can you please confirm if it is within /home that you want to open this file, or is the file in your home directory? Typically the user's name is used for the directory in /home, and hence this defines the user's home directory. For example, /home/fred.

Also, can you please explain why you insist on using low-level functions for performing I/O operations? Typically newbies to C should stick to using fopen() when opening a file.

nvteighen
May 24th, 2013, 01:45 PM
char * path = "/home/testfile";
if(open(path,O_RDONLY,0)<0)
write(1,"file not open",13);


First of all, why do you want to use open and write? Unless this is homework and you're required to use system calls or you're interested in system calls (like I was doing yesterday, in order to compare the ASM output generated by gcc vs. my own ASM), it's completely pointless to use write to write into stdout... In your case, I wouldn't even use printf, but perror to print the "File not open" error message!

Second, please post some code that yields the error you're getting. "Not opening the file" may mean several things to me: 1) your file doesn't exist, 2) you get a permissions error, 3) you get nothing, 4) whatever. In fact, using perror instead of write to print the message could give us some clues about what's happening.

Third, my guess is that the mode argument (the third argument passed to open) is screwing things up, as this gets masked by umask and 0 sounds like "no permissions at all". I never used such argument when using open() for just opening a file and as I can see from the manpage, you better use the flags specified for it. Not being an open()-guru, I think the mode argument only makes sense if you're using the O_CREAT flag to create a new file if none is found.