C二进制读写文件 [英] C binary read and write file

查看:117
本文介绍了C二进制读写文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个二进制文件读取整数数组,然后每个偶数x应该变成2 * x,每个奇数x应该变成3 * x.当我这样做时,它总是读取第二个整数(即2).有什么主意吗?

I am using a binary file for reading an array of integers, then each even integer x should become 2 * x and each odd integer x should become 3 * x. When I am doing this it always read the 2nd integer (which is 2). Any idea?

#include <stdio.h>
#include <stdlib.h>

int main(void)
{    
FILE *f;

f = fopen("inputData.txt", "w+b");
int n = 5;
int i;
for (i = 1; i <= n; ++i) {
    fwrite(&i, sizeof(int), 1, f);
}
int x;
fseek(f, 0, SEEK_SET);
while (fread(&x, sizeof(int), 1, f) == 1) {
    printf("%d ", x);
    if (x % 2 == 0) {
        fseek(f, -sizeof(int), SEEK_CUR);
        x = x * 2;
        fwrite(&x, sizeof(int), 1, f);
    } else {
        fseek(f, -sizeof(int), SEEK_CUR);
        x = 3 * x;
        fwrite(&x, sizeof(int), 1, f);
    }
}

fclose(f);
}

推荐答案

好吧,我不太了解发生了什么,但是在使用读/写文件时,您似乎无法信任fseekSEEK_CUR在这种情况下(我正在运行Windows,而众所周知的是,标准功能与Linux不同)

Okay, I don't really understand what's going on, but it seems that you cannot trust fseek with SEEK_CUR when using with read/write files in that case (I'm running Windows, and the standard functions are notoriously different from Linux that may be the issue)

安德鲁的答案证实了我的怀疑.我的解决方案符合标准的建议.

Andrew's answer confirms my suspicions. My solution complies to what the standards recommend.

解决此问题的方法是我自己管理文件位置并寻求该位置,而不是在调用fseek时隐式依赖当前文件位置.

What I have done to workaround the problem is to manage file position myself and seek to that position instead of implicitly relying on current file position when calling fseek.

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
 FILE *f;

f = fopen("inputData.txt", "w+b");
if (!f) { perror("cannot create input"); exit(1); }

int n = 5;
int i;
for (i = 1; i <= n; ++i) {
    fwrite(&i, sizeof(int), 1, f);
}


int x;
int pos=0;
fseek(f, 0, SEEK_SET);
while (fread(&x, sizeof(int), 1, f) == 1) {
    if (fseek(f, pos, SEEK_SET)) {perror("cannot seek");exit(1);}
    pos += sizeof(int);
    printf("%d %lu\n", x, ftell(f));
    if (x % 2 == 0) {
        x = x * 2;
    } else {
        x = 3 * x;
    }
    if (fwrite(&x, sizeof(int), 1, f) != 1) {perror("cannot write");exit(1);}
    if (fseek(f, pos, SEEK_SET)) {perror("cannot seek");exit(1);}
}

fclose(f);
}

现在程序的输出为(具有当前偏移量)

now the output of the program is (with current offset)

1 0
2 4
3 8
4 12
5 16

现在二进制文件的内容(在小端架构上是预期的):

contents of the binary file is now (as expected on a little endian architecture):

03 00 00 00 04 00 00 00 09 00 00 00 08 00 00 00 0F 00 00 00

因此,这是一种解决方法,但至少可以正常使用.

So this is a workaround but at least it works properly.

这篇关于C二进制读写文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆