hi.
i have problem with following code:
when i give address directly it works correct but when i get address from command line, it does n't work.

int main(int argc, char** argv)
{
    int size;
    int fd,fd2;
    char buf[10000],buf2[10000],FileAdd[10000];

        size = read(fd2,buf2,10000);
        //char *FileAdd = malloc(size);
        strcpy(FileAdd,buf2);
        if ((fd= open(FileAdd, O_RDONLY)) < 0)
        {
            perror("unable to open.");
            exit(1);
        }
        read(fd, buf, 10000);
        puts(buf);  

        int filedesc = open("writer.txt", O_WRONLY | O_APPEND);
        if (filedesc < 0)
        {
                return -1;
            }
            if (write(filedesc, buf, strlen(buf)) != strlen(buf)) {
                write(2, buf, strlen(buf));
                return -1;
            }

    return 0;
}  

Your code isn't retrieving anything from the command line; argv and argc are unused.

However, I'm not surprised at all that it doesn't work, given that you haven't initialized fd2 to anything. Presumably you wanted to read the "address" from stdin rather than command line parameters, in which case fd2 should be set to 0 (or ideally STDIN_FILENO if you've included <unistd.h>).

Edited 3 Years Ago by deceptikon

when you use read in your code, your program stops to take input from user and i set fd and fd2 to zero but still does n't work

when you use read in your code, your program stops to take input from user

I'm well aware of what read() does.

i set fd and fd2 to zero but still does n't work

fd is set by open(), but fd2 is uninitialized in the code you've provided. Unless your compiler gives it a default value of 0 (some do, but most don't), that means you're telling read() to read from a garbage file descriptor.

What exactly do you mean by "doesn't work"? Print out the contents of buf2 after read() and see if it contains the data you want. I'm willing to bet that it doesn't.

i describe it in first line of my question. with everything in code, i add the path directly without getting input from user and it works. here working means it shows contents of the file. but when i give it from user it won't.

error is :
unable to open.: No such file or directory

Great, now print out the contents of buf2 after read() and see if it contains the data you expected. I'm still willing to bet that it doesn't.

please don't ask silly questions. there is a possibelity to copy the code and run it. of course it contains the path .

i found the answer. storing the path in size of 10000 is not working. the size must be exact for the path length.

This question has already been answered. Start a new discussion instead.