从文本文件中读取并写入二进制或十六进制文件

如何解决从文本文件中读取并写入二进制或十六进制文件

请有人告诉我为什么我经常得到核心转储分段? 当我选择 n=1 工作正常但问题是 n=2 和 n=3 但我不知道为什么。我想读取一个文本文件并返回一个文本、二进制或十六进制文件。

我编辑了代码并编译了它,我只收到一个警告,它指的是 %x,但我不在乎它,因为首先我必须解决 n==2。现在我没有核心转储错误。似乎没有错误,但我的第二个文件是空的。

int main(int argc,char *argv[])
{    
    if (argc != 3){
        printf("Use this scheme: ./executabel read_file write_file -option(-b,-t,-x)\n");
        exit(EXIT_FAILURE);
    }
    
    int fd1=open(argv[1],O_RDONLY);
        int fd2=open(argv[2],O_WRONLY | O_CREAT);
        char buffer[1024];
        int rd_count = 0;
        int wr_count = 0;
        int n;
        FILE * fpw;
        fpw = fdopen (fd2,"w");
        
        if (fd1 == -1){
        printf("Failed to open the read-file.\n");
        exit(EXIT_FAILURE);
    }
    
    if (fd2 == -1){
        printf("Failed to open the write-file.\n");
        exit(EXIT_FAILURE);
    }
    
    printf("Please choose one:\n");
    printf("1. –t forces the output file to be a text one.\n");
    printf("2. –b forces the output file to be binary.\n");
    printf("3. –x forces the output file to be a hexadecimal representation.\n");
    scanf("%d",&n);
    
    
    while ((rd_count = read(fd1,(void*) buffer,1024)) > 0){
        int bytes_wr = 0;
        while (bytes_wr != rd_count){
            if (n==1){
                    wr_count = write(fd2,(void*) (buffer+bytes_wr),rd_count-bytes_wr);
                }else if (n==2){
                    wr_count = fwrite( (void*) (buffer+bytes_wr),sizeof(float),rd_count-bytes_wr,fpw);
                }else{
                    fprintf(fpw,"%x",(void*) (buffer+bytes_wr));
                }
            if (wr_count < 0) {
                perror("Failed to write to file");
                exit(EXIT_FAILURE);
            } else {
                bytes_wr += wr_count;
            }
        }
        }

        if (rd_count < 0) {
            perror("Failed to read from file");
            exit(EXIT_FAILURE);
        }
    

    close(fd1);
        close(fd2);
        chmod(argv[2],777);
    
        exit(EXIT_SUCCESS);
        
        
}

顺便提一下,这是警告

mahsa@mahsa-G53SW:~$ gcc -o ex4.o ex4.c -Wall -Wextra
ex4.c: In function ‘main’:
ex4.c:55:23: warning: format ‘%x’ expects argument of type ‘unsigned int’,but argument 3 has type ‘void *’ [-Wformat=]
   55 |         fprintf(fpw,(void*) (buffer+bytes_wr));
      |                      ~^  ~~~~~~~~~~~~~~~~~~~~~~~~~
      |                       |  |
      |                       |  void *
      |                       unsigned int
      |                      %p

我改变这一行

 fprintf(fpw,(void*) (buffer+bytes_wr));

到这里

fprintf(fpw,"%02x",buffer[bytes_wr]);

现在我什至没有警告。似乎一切正常,但当我打开第二个文件时,它是空的。

解决方法

您的代码中有多个问题:

  1. main 的签名必须是 int main(void)int main(int argc,char *argv[])

  2. 您访问缓冲区越界。

wr_count = fwrite( (void*) (buffer+bytes_wr),sizeof(float),rd_count-bytes_wr,fd2);

当您以 bytes_wr 为 0 开始并且您有一个完整的缓冲区(rd_count 容纳 1024)时,您将写入 1024 * sizeof(float) 字节,而您的缓冲区只有 1024 字节大。在这 1024 个字节之后访问任何内存位置会导致未定义的行为。

  1. 您的文件类型不正确: 最初由 Andreas Wenzel 指出。
    int fd2=open(argv[2],O_WRONLY | O_CREAT);
...
    wr_count = fwrite( (void*) (buffer+bytes_wr),fd2);
...
    fprintf(fd2,"%x",(void*) (buffer+bytes_wr));

函数 fwritefprintf 需要一个 FILE* 类型的参数来标识文件。您传递类型为 int 的文件描述符。当被调用的函数将尝试取消引用预期的指针时,您会导致未定义的行为。

有两组 I/O 函数:

  • fopenfprintffscanffflushfwritefclose
  • openwriteclose 等。 一组需要 FILE*,而另一组需要 int。不要混为一谈。

你的编译器应该警告你这一点。如果那没有发生,您需要调高警告。对于 GCC,您可以使用 -Wall -Wextra

  1. 您没有正确打印十六进制转储:
    fprintf(fd2,(void*) (buffer+bytes_wr));

您传递的地址在这里不正确。 您可能希望将单个字节传递给 fprintf。这将是这样做的方式:

    fprintf(fd2,"%02x",buffer[bytes_wr]);

还要注意包含 02 的格式字符串以指定字段的宽度。如果没有这个,你最终可能会得到 1 位数字,并且无法在输出中看到再见边界。您还应该将 buffer 更改为 unsigned char 以防止符号扩展。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-