作者:常山他爹没有JJ2000_836 | 来源:互联网 | 2023-01-21 17:15
Imtryingtoprintanintarrayonafilebutitisgivingmeanerror.我正在尝试在文件上打印一个int数组,但它给了我一个
I'm trying to print an int array
on a file but it is giving me an error.
我正在尝试在文件上打印一个int数组,但它给了我一个错误。
write_error:Bad address.
My int array
is something like :
我的int数组是这样的:
1 2 3 4 5 6 7 8 9
And I want to print it on a file
as follows :
我想将它打印在一个文件上,如下所示:
1 2 3
4 5 6
7 8 9
This is the code I'm using :
这是我正在使用的代码:
void printToFile(int listBoard[]) {
int file_write;
char buffer[100];
char buffer2[10];
if ((file_write = open("./board.txt", O_WRONLY | O_CREAT | O_TRUNC, 0700)) <0) {
err_sys("error output file");
}
if (write(file_write, snprintf(buffer2, 10, "%d",listBoard[2]), 18) != 18){
err_sys("write_error");
}
if (close(file_write) != 0){
err_sys("error close write");
}
}
I also tried (char)
but it converts the int
to the ascii char
.
我也试过(char)但它将int转换为ascii char。
Could you tell me what I'm missing?
你能告诉我我错过了什么吗?
Edit
My file output is :
我的文件输出是:
3@\00\00펈㰙\00ጠ
Code edited :
代码编辑:
void printToFile(int listBoard[]){
int file_write;
char buffer[100];
int value;
int cOnt= 0;
char buffer2[10];
if ((file_write = open("./board.txt", O_WRONLY | O_CREAT | O_TRUNC, 0700)) <0) {
err_sys("error output file");
}
int len = snprintf(buffer2, 10, "%d", listBoard[2]);
if (write(file_write, buffer2, len) != len) {
err_sys("write_error");
}
if (close(file_write) != 0) {
err_sys("error close write");
}
}
Output file :
输出文件 :
3
Last edit
This is how I did now to print it as the output that I want
这就是我现在用它来打印它作为我想要的输出
if ((file_write = open("./board.txt", O_WRONLY | O_CREAT | O_TRUNC, 0700)) <0) {
err_sys("error output file");
}
for (int index = 0; index
But it is not doing the \n
correctly. What I'm missing?
但它没有正确地做到\ n。我错过了什么?
5 个解决方案
3
The definition of write is as follows:
写的定义如下:
ssize_t write(int fd, const void *buf, size_t count);
The definition of snprintf is as follows:
snprintf的定义如下:
int snprintf(char *str, size_t size, const char *format, ...);
Now you're feeding snprintf to where write is expecting void *buf
. i.e. the address to where the data is.
现在你正在将snprintf提供给write期望void * buf的地方。即数据所在的地址。
So you'll have to do
所以你必须这样做
snprintf(buffer2, 10, "%d", listBoard[2]);
then
write(file_write, buffer2, 18);
EDIT:
That will fix the syntax error. Now semantically you can see that you're writing 10 bytes to buffer2 but you're writing 18 to the file. This will fill the file with junk. So i suggest.
这将修复语法错误。现在在语义上你可以看到你正在向buffer2写入10个字节,但是你正在写18个文件。这将用垃圾填充文件。所以我建议。
int len = snprintf(buffer2, 10, "%d", listBoard[2]);
write(file_write, buffer2, len);
EDIT 2:
int len = snprintf(buffer2, 1, "%d \n", ' ');
First off your format specifier has 3 bytes while you're only writing 1 byte to the buffer2. Second, why is your argument ' '
when you're supposed to give the listBoard[n]
?
首先,您的格式说明符有3个字节,而您只向缓冲区2写入1个字节。第二,为什么你的论点''你应该给listBoard [n]?