I am new to C and am trying to complete an assignment. The program should take a file name as an command line argument, then print the file contents. My program prints jumbled up text instead of the actual text in file.
I have searched all over the Internet for examples/answers to my problem and remain stuck!
What am I doing wrong?. If it can be helped, please modify my code instead of writing new code so that I will have an easier time understanding.
int main()
{
char fileName[20];
int *buffer;
int size;
// ask for file name and take input.
printf("Enter file name: ");
scanf("%s", fileName);
// open file in read mode.
FILE *fp;
fp = fopen(fileName, "r");
// If no file, show error.
if(fp == NULL)
{
printf("Error: Can't open file.\n");
return 1;
}
// count characters in file with fseek and put into size, then move the
// position of the file back to the beginning.
fseek(fp, 0, SEEK_END);
size = ftell(fp);
rewind(fp);
// allocate buffer and read file into buffer.
buffer = malloc(size+1);
fread(buffer, 1, size, fp);
// close the file.
fclose(fp);
// for loop reading array one character at a time.
for(int x = 0; x < size; x++)
{
printf("%c", buffer[x]);
}
return 0;
}
int *buffer->char *bufferx < size: Use return value offreadinstead ofsize. The number of actually read characters may be different.