C 打印off\t

C 打印off\t,c,linux,printing,printf,stat,C,Linux,Printing,Printf,Stat,我的C代码有问题。它可以打印,但是字符太多了。 守则: #include<stdio.h> #include<inttypes.h> #include<unistd.h> #include<sys/types.h> #include<sys/stat.h> #include<unistd.h> #include<stdlib.h> struct st

我的C代码有问题。它可以打印,但是字符太多了。 守则:

    #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;
}

您有以下声明:

char ,,,, *no;
然后你有一行:

sprintf( no, "%d", n);
代码中没有为
no
分配内存的地方。这会导致未初始化的局部变量具有不确定的值,并且您正在将其写入看似随机的内存中

我不知道这是你问题的原因,但不明确的行为会导致各种奇怪的症状


您或者需要使用例如
malloc
为变量分配内存,或者将其设置为一个数组(由十个字符组成,这是
以后编写的)。

无法复制(在添加必要的标题后,修复
main
以返回
int
并添加错误检查)。你得到了什么编译器警告?您打开了警告,不是吗?您显示的代码真的是生成该输出的代码吗?这应该是不可能的。还有一件小事情(不相关):您不需要强制转换
argv[1]
,编译器应该在没有警告的情况下处理它。非常感谢。我已将
char*no`更改为char no[10],不再有错误。新的问题是它只从管道中读取第一次。因此,如果我得到超过1个参数,那么父参数将继续打印第一个参数的结果。
sprintf( no, "%d", n);