我的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
答案 0 :(得分:1)
你有这个声明:
char ,,,, *no;
然后你有这一行:
sprintf( no, "%d", n);
代码中没有为no
分配内存。这导致undefined behavior因为未初始化的局部变量具有不确定的值,并且您正在写出看似随机的内存。
我不知道这是导致问题的原因,但未定义的行为可能会导致各种奇怪的症状。
您需要使用例如malloc
为变量分配内存,或者将其设为一个数组(十个字符,就像之后write
那样)。