c - 打印off_t

标签 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 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;
}

这是完整的代码。我知道它不是很优雅,但我没有找到更好的解决方案来打印 st_size。我尝试将其转换为字符串,但这也不起作用。如果参数是文件,它不会通过管道读取任何内容。 输出:

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

最佳答案

您有此声明:

char ,,,, *no;

然后你就会看到这一行:

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

代码中没有任何地方为no分配内存。这导致 undefined behavior因为未初始化的局部变量具有不确定的值,并且您正在写入看似随机的内存。

我不知道这是问题的原因,但未定义的行为可能会导致各种奇怪的症状。

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

关于c - 打印off_t,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23445345/

相关文章:

C 指针、最小值和最大值

linux - 使用IP_HDRINCL需要填写什么

Linux 查找文件夹并重命名

c# - 如何在 C# 中获取队列中打印作业的文件路径

html - 如何阻止 HTML/CSS 在页面之间将一行文本分成两半进行打印?

c 字符串数组维度

c - 如果没有收到 FIN/ACK 或 RST,如何终止 tcp 服务器程序中的 tcp 连接

c - 在 C 函数的参数中声明变量

c - 遍历文件系统时内存损坏

linux - 在 linux X11 问题中使用 java.awt 库