热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

无法将int打印到文件中-Can'tprintaninttoafile

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 个解决方案

#1


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]?

#2


2  

Use dprintf() to write formatted strings to files:

使用dprintf()将格式化的字符串写入文件:

dprintf(file_write, "%d", listBoard[2]);

dprintf will handle all the write stuff for you, so this is the only call you need with open and close.

dprintf将为您处理所有写入内容,因此这是您打开和关闭时唯一需要的调用。

dprintf is the fprintf for file descriptors. More informations here: https://linux.die.net/man/3/dprintf

dprintf是文件描述符的fprintf。更多信息:https://linux.die.net/man/3/dprintf

#3


0  

The snprintf (and family) functions returns an integer.

snprintf(和family)函数返回一个整数。

You use this integer in the write call as a pointer to a buffer. That will lead to undefined behavior.

您在write调用中使用此整数作为指向缓冲区的指针。这将导致不确定的行为。

Call snprintf separately, and then pass buffer2 as the second argument. And use strlen to get the actual length of the string in buffer2, not hard-code the magic number 18 which will lead to reading from out-of-bounds and another case of UB.

分别调用snprintf,然后传递buffer2作为第二个参数。并使用strlen来获取buffer2中字符串的实际长度,而不是硬编码将导致从越界读取和另一个UB情况的幻数18。

#4


0  

First of all snprintf returns an integer that is the number of chars that would have been written if the string were not truncated (as you can read on the snprintf manual)

首先,snprintf返回一个整数,该整数是字符串未被截断时已写入的字符数(正如您可以在snprintf手册中看到的那样)

you cannot then use it in the write command. You can then use:

你不能在write命令中使用它。然后你可以使用:

 if ( snprintf(buffer2, 10,"%d",listBoard[2]) >= 10 ) {
    /* handle truncation error*/
 }
 if(write(file_write,buffer2,18)!=18){
     err_sys("write_error");

Anyway since buffer2 is maximum 10 characters why do you expect to write 18 bytes?

无论如何,因为buffer2最多10个字符,你为什么要写18个字节?

Other possible error: buffer2 should be at least of 10 + 1 byte for null termination.

其他可能的错误:对于空终止,buffer2应至少为10 + 1字节。

#5


0  

You never specify that you must use raw file descriptors, so let's port your code up one level to C's standard library's FILE abstraction. It's easier to work with.

您从未指定必须使用原始文件描述符,因此让我们将您的代码上移一级到C的标准库的FILE抽象。它更容易使用。

void printToFile(const int listBoard[]) {
  FILE * const out = fopen("board.txt", "wt");
  if (out == NULL) {
    err_sys("error output file");
  }
  for(int j = 0; j <3; ++j) {
    for (int i = 0; i <3; ++i)
      fprintf(out, "%d ", listBoard[3 * j + i]);
    fprintf(out, "\n");
  }
  fclose(out);
}

Note that this uses loops to iterate over the elements of the board array, this seemed to be missing from your original code and part of the problem you had with it.

请注意,这使用循环来迭代板数组的元素,这似乎是原始代码中缺少的,也是您使用它的部分问题。

This prints:

1 2 3 
4 5 6 
7 8 9 

There's a trailing space on each line due to me being lazy, but hopefully that's fine. Also I omitted some inner error checking.

由于我很懒,每条线都有一个尾随空间,但希望这很好。我也省略了一些内部错误检查。


推荐阅读
  • 本文讨论了如何使用GStreamer来删除H264格式视频文件中的中间部分,而不需要进行重编码。作者提出了使用gst_element_seek(...)函数来实现这个目标的思路,并提到遇到了一个解决不了的BUG。文章还列举了8个解决方案,希望能够得到更好的思路。 ... [详细]
  • Python正则表达式学习记录及常用方法
    本文记录了学习Python正则表达式的过程,介绍了re模块的常用方法re.search,并解释了rawstring的作用。正则表达式是一种方便检查字符串匹配模式的工具,通过本文的学习可以掌握Python中使用正则表达式的基本方法。 ... [详细]
  • Go Cobra命令行工具入门教程
    本文介绍了Go语言实现的命令行工具Cobra的基本概念、安装方法和入门实践。Cobra被广泛应用于各种项目中,如Kubernetes、Hugo和Github CLI等。通过使用Cobra,我们可以快速创建命令行工具,适用于写测试脚本和各种服务的Admin CLI。文章还通过一个简单的demo演示了Cobra的使用方法。 ... [详细]
  • 本文讨论了clone的fork与pthread_create创建线程的不同之处。进程是一个指令执行流及其执行环境,其执行环境是一个系统资源的集合。在调用系统调用fork创建一个进程时,子进程只是完全复制父进程的资源,这样得到的子进程独立于父进程,具有良好的并发性。但是二者之间的通讯需要通过专门的通讯机制,另外通过fork创建子进程系统开销很大。因此,在某些情况下,使用clone或pthread_create创建线程可能更加高效。 ... [详细]
  • 本文讨论了在openwrt-17.01版本中,mt7628设备上初始化启动时eth0的mac地址总是随机生成的问题。每次随机生成的eth0的mac地址都会写到/sys/class/net/eth0/address目录下,而openwrt-17.01原版的SDK会根据随机生成的eth0的mac地址再生成eth0.1、eth0.2等,生成后的mac地址会保存在/etc/config/network下。 ... [详细]
  • 海马s5近光灯能否直接更换为H7?
    本文主要介绍了海马s5车型的近光灯是否可以直接更换为H7灯泡,并提供了完整的教程下载地址。此外,还详细讲解了DSP功能函数中的数据拷贝、数据填充和浮点数转换为定点数的相关内容。 ... [详细]
  • 本文介绍了Swing组件的用法,重点讲解了图标接口的定义和创建方法。图标接口用来将图标与各种组件相关联,可以是简单的绘画或使用磁盘上的GIF格式图像。文章详细介绍了图标接口的属性和绘制方法,并给出了一个菱形图标的实现示例。该示例可以配置图标的尺寸、颜色和填充状态。 ... [详细]
  • IOS开发之短信发送与拨打电话的方法详解
    本文详细介绍了在IOS开发中实现短信发送和拨打电话的两种方式,一种是使用系统底层发送,虽然无法自定义短信内容和返回原应用,但是简单方便;另一种是使用第三方框架发送,需要导入MessageUI头文件,并遵守MFMessageComposeViewControllerDelegate协议,可以实现自定义短信内容和返回原应用的功能。 ... [详细]
  • Python操作MySQL(pymysql模块)详解及示例代码
    本文介绍了使用Python操作MySQL数据库的方法,详细讲解了pymysql模块的安装和连接MySQL数据库的步骤,并提供了示例代码。内容涵盖了创建表、插入数据、查询数据等操作,帮助读者快速掌握Python操作MySQL的技巧。 ... [详细]
  • Ihaveaworkfolderdirectory.我有一个工作文件夹目录。holderDir.glob(*)>holder[ProjectOne, ... [详细]
  • OpenMap教程4 – 图层概述
    本文介绍了OpenMap教程4中关于地图图层的内容,包括将ShapeLayer添加到MapBean中的方法,OpenMap支持的图层类型以及使用BufferedLayer创建图像的MapBean。此外,还介绍了Layer背景标志的作用和OMGraphicHandlerLayer的基础层类。 ... [详细]
  • Python已成为全球最受欢迎的编程语言之一,然而Python程序的安全运行存在一定的风险。本文介绍了Python程序安全运行需要满足的三个条件,即系统路径上的每个条目都处于安全的位置、"主脚本"所在的目录始终位于系统路径中、若python命令使用-c和-m选项,调用程序的目录也必须是安全的。同时,文章还提出了一些预防措施,如避免将下载文件夹作为当前工作目录、使用pip所在路径而不是直接使用python命令等。对于初学Python的读者来说,这些内容将有所帮助。 ... [详细]
  • 使用freemaker生成Java代码的步骤及示例代码
    本文介绍了使用freemaker这个jar包生成Java代码的步骤,通过提前编辑好的模板,可以避免写重复代码。首先需要在springboot的pom.xml文件中加入freemaker的依赖包。然后编写模板,定义要生成的Java类的属性和方法。最后编写生成代码的类,通过加载模板文件和数据模型,生成Java代码文件。本文提供了示例代码,并展示了文件目录结构。 ... [详细]
  • 本文介绍了在PostgreSQL中批量导入数据时的优化方法。包括使用unlogged表、删除重建索引、删除重建外键、禁用触发器、使用COPY方法、批量插入等。同时还提到了一些参数优化的注意事项,如设置effective_cache_size、shared_buffer等,并强调了在导入大量数据后使用analyze命令重新收集统计信息的重要性。 ... [详细]
  • 流数据流和IO流的使用及应用
    本文介绍了流数据流和IO流的基本概念和用法,包括输入流、输出流、字节流、字符流、缓冲区等。同时还介绍了异常处理和常用的流类,如FileReader、FileWriter、FileInputStream、FileOutputStream、OutputStreamWriter、InputStreamReader、BufferedReader、BufferedWriter等。此外,还介绍了系统流和标准流的使用。 ... [详细]
author-avatar
常山他爹没有JJ2000_836
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有