-3

could someone please explain me, why file opening is not successful? why printing "file" will give -1? Is it a problem with char *source?

int opf(char *source){
    int file;
    file=open(source,O_RWR);
    printf("%d",file); 
}

And is it possible to do something like this: file is in another directory, so

int opf(char *source){
    int file;
    file=open("some_directory/ %s",source,O_RWR);
    printf("%d",file); 
}

here I get the "makes integer from pointer without a cast" error. I tried many different things but i guess the problem lies with me not grasping correctly the concepts.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
letter
  • 91
  • 1
  • 7

1 Answers1

8

From the man page of open() (emphasis mine)

Upon successful completion, the function shall open the file and return a non-negative integer representing the lowest numbered unused file descriptor. Otherwise, -1 shall be returned and errno set to indicate the error. No files shall be created or modified if the function returns -1.

So, in your case, the open() has failed. Check for the errno to get more details on that. All the possible values for errno is also documented in the linked page.

That being said,

  1. O_RWR does not seem to be a valid mode,O_RDWR is.
  2. For the second approach, you can use sprintf()/snprintf() first to create the path string and then you can pass that to open().
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261