Question

I have a problem with my C code. It prints, but way too many characters. The code:

    #include<stdio.h>
    #include<inttypes.h>
    #include<unistd.h>
    #include<sys/types.h>
    #include<sys/stat.h>
    #include<unistd.h>
    #include<stdlib.h>
    struct stat buff;
    int main(int argc, char *argv[])
    {
      int p, i, fd[2], n;
      char message[10], *file, *no;
      pipe(fd);
      for(i = 1; i < = argc; i++)
      {p = fork();
       if ( p == 0 )
       {
         close ( fd[0] );
         if ( access( argv[i], F_OK ) != -1 )
            {printf( "%s is an existing file \n", argv[i] );
             fflush( stdout );

             stat( (const char*)argv[i] , &buff );
             printf( "%lld", (long long)buff.st_size );
             fflush( stdout );

             //sprintf( file , "%lld" , (long long)buff.st_size);
             //write( fd[1], file /*&buff->st_size*/ ,10 );
            }
         else if ( opendir ( argv[i] ) != NULL )
                {printf("%s is an existing directory \n", argv[i]);
                 fflush(stdout);
                }
                else
                  { srand( time(NULL));
                    n = rand()%11+5;
                    sprintf( no, "%d", n);
                    printf( "%s randomly number \n", no );
                    fflush( stdout );
                    write( fd[1], no /*sizeof((char*)(((int)'0')+n))*/, 10);
                  }
         close ( fd[1] );
         exit(0);
       }
      else
        if ( p == -1 )
            {
                printf( "error" );
                exit(1);
            }
        close( fd[1] );
        read ( fd[0] , message , 10 );
        printf ( "%s \n" , message );
        fflush ( stdout );
        close ( fd[0] );
        wait(0);
    }
   return 0;
}

This is the entire code. I know it is not very elegant, but I didn't find a better solution for printing the st_size. I tried to convert it to string but that didn't worked either. It won't read through pipe anything if the argument is a file. The output:

    449▒▒▒▒▒▒▒▒▒▒)▒▒▒▒▒t$1▒E▒D▒E▒D$▒▒$▒▒▒▒▒▒▒▒9▒rރ▒[^_]Ë$Ð▒U▒▒S▒▒▒E
Was it helpful?

Solution

You have this declaration:

char ,,,, *no;

And then you have this line:

sprintf( no, "%d", n);

Nowhere in the code do you allocate memory for no. This leads to undefined behavior as uninitialized local variables have indeterminate values, and you are writing out into seemingly random memory.

I don't know it this is the cause of your problem, but undefined behavior can cause all kind of weird symptoms.

You either need to use e.g. malloc to allocate memory for the variable, or make it an array (of ten characters, as that's what you write later).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top