为什么FWRITE写的比我告诉它? [英] Why is fwrite writing more than I tell it to?

查看:190
本文介绍了为什么FWRITE写的比我告诉它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

FILE *out=fopen64("text.txt","w+");
unsigned int write;
char *outbuf=new char[write];
//fill outbuf
printf("%i\n",ftello64(out));
fwrite(outbuf,sizeof(char),write,out);
printf("%i\n",write);
printf("%i\n",ftello64(out));

输出:

0
25755
25868

这是怎么回事?
写设置为25755,我告诉fwrite来很多字节写入一个文件,这是开头,然后在位置为IM除了25755?

what is going on? write is set to 25755, and I tell fwrite to write that many bytes to a file, which is at the beginning, and then im at a position besides 25755?

推荐答案

如果你是一个DOSish系统上(比如Windows),然后该文件不以二进制模式打开,行结束时会自动转换,每个行将增加一个字节。

If you are on a DOSish system (say, Windows) and the file is not opened in binary mode, line-endings will be converted automatically and each "line" will add one byte.

所以,指定WB的模式,而不是仅仅W作为@caf指出。这将有类似的平台上的Unix没有影响,做别人的事情。

So, specify "wb" as the mode rather than just "w" as @caf points out. It will have no effect on Unix like platforms and will do the right thing on others.

例如:

#include <stdio.h>

#define LF 0x0a

int main(void) {
    char x[] = { LF, LF };

    FILE *out = fopen("test", "w");

    printf("%d", ftell(out));
    fwrite(x, 1, sizeof(x), out);
    printf("%d", ftell(out));

    fclose(out);
    return 0;
}

用VC ++


C:\Temp> cl y.c
Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 15.00.21022.08 for 80x86
Copyright (C) Microsoft Corporation.  All rights reserved.

y.c
Microsoft (R) Incremental Linker Version 9.00.21022.08
Copyright (C) Microsoft Corporation.  All rights reserved.

/out:y.exe

C:\Temp> y.exe
04

在Cygwin的海湾合作​​委员会:


/cygdrive/c/Temp $ gcc y.c -o y.exe

/cygdrive/c/Temp $ ./y.exe
02

这篇关于为什么FWRITE写的比我告诉它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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