Search code examples
cfilestructfile-writing

data written to txt file appears in some bizzare language[C]


So I've written a program that will take in a information about a dvd (specifically it's postion, IDkey(just some random number) Title, Genre and Year of release), and using a struct it will write that info to a .txt file called "person.txt". I'm positive my code works for the most part but when I go to test it the output received in the .txt file is written in some weird symbol language and not English and quite frankly I have no idea as to why this is. Any explanation on why this is happening would be much appreciated, thanks :)

PROGRAM

#include <stdio.h>
#include <stdlib.h>

// a struct to read and write
struct dvd
{
    int fposition;
    int fIdKey;
    char ftitle[50];
    char fgenre[50];
    int fyear;
};

int main ()
{
    FILE *outfile;
    struct dvd input;

    // open file for writing
    outfile = fopen ("person.txt", "w");
    if (outfile == NULL)
    {
        fprintf(stderr, "\nError opend file\n");
        exit (1);
    }


    printf("Postion: ");
    scanf("%d", &input.fposition);

    printf("ID Key: ");
    scanf("%d", &input.fIdKey);

    printf("Title: ");
    scanf("%s",&input.ftitle);

    printf("Genre: ");
    scanf("%s", &input.fgenre);

    printf("Year: ");
    scanf("%d", &input.fyear);

    // write struct to file
    fwrite (&input, sizeof(struct dvd), 1, outfile);

    if(fwrite != 0)
        printf("contents to file written successfully !\n");
    else
        printf("error writing file !\n");

    // close file
    fclose (outfile);

    return 0;
}

TEST RUN

TEST RUN OUTPUT IN THE .TXT FILE


Solution

  • You are writing these values to the file:

    int fposition;
    int fIdKey;
    char ftitle[50];
    char fgenre[50];
    int fyear;
    

    But you are displaying the whole file as characters. That kind of works for ftitle and fgenre because they really are characters...though since you don't populate all 50 characters there are some ugly uninitialized characters shown as well. That is easy to fix: just fill the unused characters (as well as the null terminator) with some known character (such as space) before writing to the file, or do not write the unused characters at all. You can use strlen() to find the length of each string and memset() to set the unused characters to a well-known character which is printable.

    Next, saving an int and reading it as text is problematic. You need to decide on a single format. Either you write as integers like now, and you read as integers (which means you need a special program to read the file), or you commit to writing only text to the file.

    Easiest might be to only write text to the file. You can use fprintf() for that, instead of fwrite(). You can use fprintf() for the character arrays as well, it will automatically write only the "used" part of each string up to the null terminator, skipping all the "garbage" characters.