Angry Man
Angry Man

Reputation: 1

How to pass string as well as file to be used by open function in C?

I have a function which take filename as input and do "open" and "read" calls to perform some operation. This filename is received via command line argument. Now, I am trying to make this function generic so that it can receive string as well and perform the same operations. In other way I am passing the content of file directly as string.

I don't know how to stream the string data to the "open" function. Also, please note that I am restricted to use the open function for file read.

I tried "pipe" function to stream data to open function, but was not successful.

int sopen(char *s) {
    int p[2], ret;
    int fd=-1;
    int len  = strlen(s);

    if (pipe(p) != 0) {
        fprintf(stderr, "Error in creating pipe");
        return -1;
    }

    if ((fd = open(p[0], O_RDONLY)) < 0) {
        fprintf(stderr, "Error in open");
        close(p[0]);
        close(p[1]);
        return -1;
    }

    ret = write(p[1], s, len);
    if (ret != len) {
        fprintf(stderr, "Error in writing to pipe");
        close(p[1]);
        close(fd);
        return -1;

    }
    close(p[1]);

    return fd;
}

I expect a file descriptor so that it can be used by the open function, but it is returning -1.

Upvotes: 0

Views: 266

Answers (1)

quetzalcoatl
quetzalcoatl

Reputation: 33566

As others said, the pipe() function returns two descriptors that are already ready-to-use. That means, the pipe() already opens them for you. Otherwise it could not guarantee that these are conected to each other.

Remember that you are responsible for closing both of them!

Your whole solution should like something close to this pseudocode below:

main
   variable: fileDescriptor

   detect if command line contains a filename, or file content
   if it was a filename
      fileDecriptor = openFile(some arguments...)
   if it was a filecontent
      fileDecriptor = openAndFillPipe(some other arguments...)

   doWhetever(fileDescriptor) // here's the 'operations' on the 'file'

   close(fileDescriptor) // whatever we got, we need to clean it up


openFile(filename)
    // simply: any file-opening will do
    descriptor = open(filename, ...)


openAndFillPipe(filecontent)
    // first, make a pipe: two connected descriptors
    int pairOfDescriptors[2];
    pipe(pairOfDescriptors);

    // [0] is for reading, [1] is for writing
    write(pairOfDescriptors[1], filecontent, ...) // write as if to a file

    close(pairOfDescriptors[1])  // we DONT need the 'write' side anymore

    descriptor = pairOfDescriptors[0] // return the 'read' as if it was a file

Upvotes: 1

Related Questions