I have an assignment to create my own version of UNIX ar, in C. I broke the assignment up into several pieces and I am just trying to write the file names into another file(which will be my archive file) at this point. I can create the file, and when I use printfs to make sure I'm getting the proper arguments from the command line, the file names are correct. When I open the file that I have created that is suppose to hold those file names, everything is in an Asian language.
I've researched the problem and haven't found much to go on. The only thing I did find was something about the files being encoded differently, but I'm pretty confused at this point.
#include <stdlib.h>
#include "ar.h"
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main (int argc, char **argv)
{
char *file_name, *archive_name;
size_t count = 50;
int i, fd, num_written;
//command line options to do later
//argv[1]
//get archive name
archive_name = argv[2];
//get file names to add to archive
for (i = 3; i<argc; i++)
{
file_name = argv[i];
}
//create archive file
fd = open(archive_name, O_RDWR |O_CREAT|O_APPEND);
if (fd < 0){
perror("Error while opening file.\n");
exit(EXIT_FAILURE);
}
else
printf("File %s opened successfully\n", archive_name);
//write file names into archive file
for (i = 3; i<argc; i++)
{
printf("file name: %s\n", argv[i]);
num_written = write(fd, argv[i], 50);
if (num_written == -1){
perror("Error while writing to archive.\n");
exit(EXIT_FAILURE);
}
}
close(fd);
return 0;
}
Your code is assuming all arguments after the archive name are 50 bytes long. If the arguments are shorter than that, the program may crash or write random data. Since it didn't crash, and Notepad (or whatever) seems to think it's Chinese, I'm going to assume it wrote the random data. Use strlen
to figure out how long each of the argument names are.
Additionally:
you check argv[2]
without checking argv
, which could cause a crash.
Nothing you do with file_name
makes any sense.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments