I am trying to read the contents of a file into a char array and then print that array and so far it actually works but it not only prints the array but also "Segmentation fault. (core dumped)". Here is the code I am using.
Code:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]){
if (argc != 3){
printf("Usage: %s <input filename> <file to write to>\n", argv[0]);
}
else {
FILE *ifile = fopen(argv[1], "r");
FILE *ofile = fopen(argv[2], "w");
if (!ifile){
printf("Error: Could not open input file \n");
}
else {
if(!ofile){
printf("Error: Could not write to file %s", argv[2]);
}
else {
int length = 0;
int i = 0;
while(fgetc (ifile) != EOF){
length++;
}
char input[] = "";
rewind(ifile);
for(i = 0; i < length; i++){
input[i] = fgetc(ifile);
}
printf("%s",input);
}
}
}
return 0;
}
I am guessing it does not work because I didn't initialize the length of the input[] array correctly, but how would I go about doing that?