Вопрос

Trying to send a table of integers to file, but I'm getting some errors:

        fd[0] = open(argv[1], O_WRONLY|O_CREAT|O_SYNC, 0700);
        const int size = 20;
        int *p = new int[size];
        for(int i=0; i<size; i++) {
            p[i] = i;
        }
        write (fd[0], p, sizeof(int)*size); 
        close(fd[0]);

After calling this code in my file I see something like this: \00\00\00\00\00\00\00.

Это было полезно?

Решение 2

When you write datas in files, if you want to read it with a text editor, you need to convert variables to strings (serialization).

To do this, you can use fprintf and fscanf, or implement your own parsing functions, you only need to manipulate strings.

In order to generate a readable file, your code could be modified in:

FILE *f = fopen(argv[1], "w"); // "a", "w" or what you want
const int size = 20;
int *p = new int[size];
for(int i=0; i<size; i++) {
  p[i] = i;
  fprintf(f, "%d ", p[i]); 
}

fclose(f);

To read the file, you could do:

FILE *f = fopen(argv[1], "r");
int nb = 0;
int tab[100]; // a buffer

while((1 == fscanf("%d ", &tab[nb])) && (nb < 100))
  nb++;

Другие советы

This will write space separated integers, with a trailing space. You didn't really say what format you need other than "text".

    fd[0] = open(argv[1], O_WRONLY|O_CREAT|O_SYNC, 0700);
    if(fd[0] < 0) {
        perror("open");
    }
    const int size = 20;
    //int *p = new int[size];
    for(int i=0; i<size; i++) {
        char buf[20];
        snprintf(buf, sizeof(buf), "%d ", i);
        write(fd[0], buf, strlen(buf));
    }
    //write (fd[0], p, sizeof(int)*size); 
    close(fd[0]);
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top