简体   繁体   中英

Using C (syscall) to write an integer matrix into a text file?

So, I have my matrix, let's say int matC[N][N], which is already filled with integer values.

What I have to do is to save this matrix into a .txt file. I've tried this:

1: convert the integers contained in the matrix into a string

char *buffer;
for (int i = 0 ; i < N ; i++)
{
    for (int j = 0 ; j < N ; j++)
    {
        snprintf(buffer, sizeof(matC[i][j]), "%d", matC[i][j]);
    }
}

2: write the string in a file (fileC.txt)

int fdC = open("fileC.txt", O_RDWR);
write(fdC, buffer, sizeof(buffer));

I do get something in my fileC.txt, but it's some sort of bunch of unintelegible symbols. Thanks in anticipation for any help.

A few things.

First, you need to allocate memory for your buffer. sizeof(buffer) will be the size of a pointer, not the buffer length, so you you store that in buf_len . Depending on how many digits the numbers in your matrix are, you might need more or less space in your buffer.

Then, you don't want to write to the beginning of buffer with each snprintf call, but strchr(buffer, '\\0') will return a pointer to the spot you want to write to. The second argument should be the length of the buffer from the spot you're currently at, which is buf_len - strlen(buffer) .

Finally, you only want to write strlen(buffer) bytes to the file so you don't write random bytes to your file.

char    *buffer;
int     buf_len = 100;


buffer = (char*)malloc(buf_len);
buffer[0] = '\0';
for (int i = 0 ; i < N ; i++)
{
    for (int j = 0 ; j < N ; j++)
    {
        snprintf(strchr(buffer, '\0'), buf_len - strlen(buffer), "%d", matC[i][j]);
    }
}

int fdC = open("fileC.txt", O_RDWR);
write(fdC, buffer, strlen(buffer));
free(buffer);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM