What's wrong with my code? (Printing File names inside an Archive File)

亡梦爱人 提交于 2019-12-13 20:08:20

问题


I'm trying to write a program to open an archive file from Unix, read the files in and print what files are inside the archive and just the filename. Below is my code -- it compiles, but I got some weird output in the terminal -- e.g. ?;?U?. It should just display 2 txt file names. Can someone take a look at my code and give me some guidance on what I'm missing? Thank you!

EDIT: I made some changes to my code, but it's still not working. Any suggestion or help is greatly appreciated.

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/utsname.h>
#include <ctype.h>
#include <string.h>
#include <ar.h>


int main (int argc, char **argv)
{
    int input_fd;
    //char buffer[25];

    struct ar_hdr my_ar;

    if (argc != 2) {
        printf("Error", argv[0]);
        exit(EXIT_FAILURE);
    }


    //open the archive file (e.g., hw.a)
    input_fd = open(argv[1], O_RDONLY);
    if (input_fd == -1)
    {
        perror("Can't open input file\n");
        exit(-1);
    }

    while (read(input_fd, my_ar.ar_name, sizeof(buffer)) > 0) {
        printf("%s\n", my_ar.ar_name);
    }

    close(input_fd);

    return 0;
}

回答1:


I don't see anywhere that you are defining what a my_hdr is, yet you are printing one of its supposed members here:

printf("%s\n", my_ar.ar_name);

You also never set ar_name to anything either.

I see you read some data into a variable named buffer, but you never actually copy that buffer into ar_name which I am assuming is your intent.

while (read(input_fd, buffer, sizeof(buffer)) > 0) {
    printf("%s\n", my_ar.ar_name);
}



回答2:


The POSIX documentation explicitly states that the archive file format is not described, on the grounds that several incompatible such formats already exist, so you'll definitely need to study the documentation provided by your OS if you're going to use <ar.h> instead of the ar command-line utility.

Here are some details that might help, based on the Solaris implementation:

  1. An archive file starts with a magic cookie string which you are neither verifying nor skipping,
  2. Each header object is followed by the content of the actual object in the archive, which you are not stepping over,
  3. The first object in the archive is an unnamed object containing the archive's symbol table,
  4. If an object's name is more than fifteen bytes long, it will be stored in the archive's string table, which appears to be part of the symbol table.

Note that these points, or details thereof, may vary on your OS. As I said at the beginning, study the documentation provided by your OS.



来源:https://stackoverflow.com/questions/17712011/whats-wrong-with-my-code-printing-file-names-inside-an-archive-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!