In: Computer Science
C Programming
file.c takes in one input argument that denotes a file to be read. It needs to convert the contents of that file into a character array (char *) and then into a an unsigned character array (unsigned char *).
Please fix and or complete the program, and explain any of the changes too:
----
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
FILE *f; f = fopen(argv[1], "r");
if( !f ) { exit(1); }
char *tok;
char buf[256];
char *save; // saved data
while(fgets(buf, sizeof(buf), f)
{
tok = strtok(buf, "\0");
save = strcat(save, tok);
}
printf("%s", save); // prints contents
// convert save into an unsigned character array (unsigned char
*)
}
----
example.txt // sample text to convert, varies in size/length, can have multiple lines
Hello world.
Have a nice day!
----
run the program (in UNIX) as an executable:
file example.txt // takes in one argument only
Please look at my code and in case of indentation issues check the screenshots.
------------main.c-----------------
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
if (argc != 2){
//checks if there are 2
command line arguments ./a.out and filename
printf("Please provide filename as
command line argument\n");
exit(1);
}
FILE * f;
f = fopen(argv[1], "r");
if (!f)
//report if file cannot be opened
{
printf("The input file cannot be
opened\n");
exit(1);
}
char buf[256];
//buffer to read a line of
data from file
char *save = malloc(sizeof(char) * 1024);
//allocate space for storing 1024 characters in the array
while (fgets(buf, sizeof(buf), f))
//read a line into buf
{
save = strcat(save,
buf);
//append the line into the char array save
}
save[strlen(save)] = '\0';
//set last character as null character
printf("%s\n", save); // prints
contents
unsigned char *save2 = malloc(sizeof(unsigned char)
* 1024); //allocate space for storing 1024 unsigned characters in
the array
int i;
for(i = 0; i < strlen(save); i++)
//loop for each index of save array
{
save2[i] = save[i];
//copy the contents from char
array save to unsigned char array save2
}
save2[i] = '\0';
//set last character as null
character
printf("\n%s\n", save2); // prints
contents
}
--------------Screenshots-------------------
----------------------Input--------------------------------------
----------------------Output------------------------------------
-------------------------------------------------------------------------------------------------------------
Please give a thumbs up if you find this answer helpful.
If it doesn't help, please comment before giving a thumbs
down.
Please Do comment if you need any clarification.
I will surely help you.
Thankyou