Marcus Hall
Marcus Hall

Reputation: 1

adding characters from text file into an array

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;
}

Upvotes: 0

Views: 106

Answers (1)

Stephan Lechner
Stephan Lechner

Reputation: 35154

You are using the wrong datatype for reading in characters, i.e. you use int *buffer, but you should use char *buffer.

When using int *buffer, an access like printf("%c",buffer[x]) will access your buffer as an array of integers; an integer is probably of size 4, such that buffer[1] addresses the 4th byte in the buffer, buffer[2] the 8th and so forth... Hence, you will read out elements that are not contained in the file any more, actually exceeding array bounds (leading to garbage or something else).

Upvotes: 2

Related Questions