我正在尝试打印文件指针的位置(通过printpos()函数),显示它在子节点和父节点中的位置。在编译我的代码时,我留下了这些错误:
xxxxxx@ubuntu:~/USP_ASG2$ gcc -o q1 q1.c
/tmp/cc4zpABN.o: In function `main':
q1.c:(.text+0xdd): undefined reference to `printpos'
q1.c:(.text+0x171): undefined reference to `printpos'
q1.c:(.text+0x1fd): undefined reference to `printpos'
q1.c:(.text+0x2a4): undefined reference to `printpos'
collect2: error: ld returned 1 exit status
代码(供参考):
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/wait.h>
int main()
{
char x[3];
x[0]='y';
int ch;
while(x[0]=='y'||x[0]=='Y')
{
int status;
pid_t pid;
int a = 123456;
float b = 123.456;
char c = 'Z';
char buff[5];
int fd = open("/proc/meminfo", O_RDONLY);
//Retriving address's
void *ap=&a, *bp=&b, *cp=&c;
printf("\n---------------Initial Values---------------\n");
printf("Parent Values:\n");
printf("Integer a: \tvalue = %d, \taddress = %p\n", a, ap);
printf("Float b: \tvalue = %f, \taddress = %p\n", b, bp);
printf("Char c: \tvalue = %c, \t\taddress = %p\n", c, cp);
printpos("Pointer Position: ", fd);
pid = fork();
if(pid > 0)
{
pid = wait(&status);
printf("\nParent Changed Values:\n");
printf("Integer a: \tvalue = %d, \taddress = %p\n", a, ap);
printf("Float b: \tvalue = %f, \taddress = %p\n", b, bp);
printf("Char c: \tvalue = %c, \t\taddress = %p\n", c, cp);
printpos("Pointer Position: ", fd);
sleep(1);
}
else if(pid == 0)
{
printf("\nChild Initial Values:\n");
printf("Integer a: \tvalue = %d, \taddress = %p\n", a, ap);
printf("Float b: \tvalue = %f, \taddress = %p\n", b, bp);
printf("Char c: \tvalue = %c, \t\taddress = %p\n", c, cp);
printpos("Pointer Position: ", fd);
a = 654321;
b = 654.321;
c = 'A';
read(fd, buff, 5);
printf("\n---------------Changed Values---------------\n");
printf("\nChild Changed Values:\n");
printf("Integer a: \tvalue = %d, \taddress = %p\n", a, ap);
printf("Float b: \tvalue = %f, \taddress = %p\n", b, bp);
printf("Char c: \tvalue = %c, \t\taddress = %p\n", c, cp);
printpos("Pointer Position: ", fd);
return 0;
}
else
printf("fork() did not work");
if(pid >0)
{
printf("Run Again?(y/n):");
fgets(x, 2, stdin);
while ( (ch = fgetc(stdin)) != EOF && ch != '\n');
}
}
return 0;
}
答案 0 :(得分:0)
您可以使用lseek
和printf
。
printf("Pointer Position: %lld\n", lseek(fd, 0, SEEK_CUR));
答案 1 :(得分:0)
这里的问题是没有名为printpos
的函数。以下是一些应该按预期执行的代码。
void printpos( char* text, int fd )
{
off_t position;
position = lseek( fd, 0, SEEK_CUR );
if( position >= 0 )
{
printf( "%s%lld\n", text, (long long)position );
}
else
{
printf( "Error getting position in file\n" );
}
}
[编辑:更新了代码以添加(long long)
的{{1}}演员,因为在某些平台上它可能是不同的类型]