user11550047
user11550047

Reputation:

Weird output from integer array to a file

Hi I am writing a program that generates random ints, put them in an array and save them to a file. Everything seems to work good but after I open this file it has this strange content : ^K^@^@^S^@^@^@^[^@ What have I done wrong?

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <time.h>

int main(int argc, char *argv[]) {
    int tab[10];
    int fd;
    srand(time(0));
    int i;
    for(i = 0; i < 10; i++)
        tab[i] = rand() % 50;
    if(argc != 2 || strcmp(argv[1], "--help") == 0)
    {
        .......
    }
    fd = open(argv[1], O_RDWR | O_CREAT | O_TRUNC, 0644);
    write(fd, tab, 10);
    close(fd);
    return 0;
}

Upvotes: 1

Views: 37

Answers (1)

Jean-Fran&#231;ois Fabre
Jean-Fran&#231;ois Fabre

Reputation: 140168

The content is wierd because you're writing binary values, random character codes from 0 to 50. But the information is there all right (well, you have to write sizeof(int) times more data to store all the data though, and it can be corrupt on Window because you're missing O_BINARY and some carriage return chars may be inserted at some locations...):

fd = open(argv[1], O_RDWR | O_CREAT | O_TRUNC, 0644); // add | O_BINARY if you use windows
write(fd, tab, 10 * sizeof(int));  // you can use (fd,tab,sizeof(tab)) too as it's an array, not a pointer

Use a hex editor you'll see the values (with a lot of zeroes since your values can be encoded in a byte). But not with a text editor.

If you want to write formatted integers as strings, use fopen and fprintf on the values, in a text file, not binary. Quick & dirty (and also untested :)):

FILE *f = fopen(argv[1], "w");  // #include <stdio.h> for this
if (f != NULL)
{
    int i;
    for (i = 0; i < 10; i++)
    {
       fprintf(f,"%d ",tab[i]);
    }
    fclose(f);
}

Upvotes: 3

Related Questions