简体   繁体   English

使用C(syscall)将整数矩阵写入文本文件?

[英]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. 所以,我有我的矩阵,让我们说int matC [N] [N],它已经填充了整数值。

What I have to do is to save this matrix into a .txt file. 我要做的是将此矩阵保存到.txt文件中。 I've tried this: 我试过这个:

1: convert the integers contained in the matrix into a string 1:将矩阵中包含的整数转换为字符串

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) 2:将字符串写入文件(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. 我确实在我的fileC.txt中得到了一些东西,但它是一些不可理解的符号。 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 . sizeof(buffer)将是指针的大小,而不是缓冲区长度,因此您将其存储在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. 然后,您不希望在每次snprintf调用时写入buffer的开头,但strchr(buffer, '\\0')将返回指向您要写入的位置的指针。 The second argument should be the length of the buffer from the spot you're currently at, which is buf_len - strlen(buffer) . 第二个参数应该是您当前所在位置的缓冲区长度,即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. 最后,您只想将strlen(buffer)字节写入文件,这样就不会将随机字节写入文件。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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