Question

int main(int argc,char *argv[])
{
    int f1,flag,n;
    if(argc<3)
    {
        printf("Correct format: ./a.out <fileName> <string>\n");
        exit(-1);
    }
    f1=creat(argv[1],0666);
    if(f1<0)
    {
        printf("Creatioon error\n");
        exit(f1);
    }
    n=strlen(argv[2]);
    printf("%d\n",n);
    while(n-->0)
    flag=write(f1,argv[2]++,1);
    if(flag<0)
    {
        printf("Write error\n");
        exit(flag);
    }
    close(f1);
    return 0;
}

here in flag=write(f1,argv[2]++,1); why do we do argv[2]++ and why is the length of the text to be copied is 1??

Was it helpful?

Solution

The increment is because it's in a (stupid) loop:

while(n-->0)
  flag=write(f1,argv[2]++,1);

but your code isn't indented so it's a bit harder to see.

argv[2] is a char * pointing at the string entered as the third word on the command-line, so incrementing it steps it to the next character in the string.

This is bad code; it should be write(fl, argv[2], n); to write it all at once. Of course, the return value must still be inspected and the write() maybe looped to try again or resume if there is a partial write.

OTHER TIPS

The length is 1 because the 3rd argument of write is 1.

You probably want this:

/* write second command line argument to the file */
flag=write(f1, argv[2], strlen(argv[2]);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top