难道在C中放回车符? [英] fread dropping carriage returns in C?

查看:109
本文介绍了难道在C中放回车符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够读取Windows文本文件,在内存中对其进行修改,然后用修改后的数据覆盖旧文件.但是,fread似乎并没有存储我的Windows文本文件中存在的回车符,当我覆盖旧数据时,这会丢掉东西.我找不到其他似乎遇到过此问题的人.

I want to be able to read in a Windows text file, modify it in memory, and then overwrite the old file with the modified data. However, fread doesn't seem to store the carriage returns present in my Windows text file, which is throwing things off when I write over the old data. I can't find anyone else who seems to have had this issue.

这是一些演示此问题的示例代码:

Here is some example code that demonstrates the problem:

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

int main()
{
    FILE* textFile;
    long fileSize;
    char fileCharacterBuffer[100];

    int i;
    for(i = 0; i < 100; i++)
    {
        fileCharacterBuffer[i] = '\0';
    }

    textFile = fopen("./Test.txt", "r+");

    fseek(textFile, 0L, SEEK_END);
    fileSize = ftell(textFile);
    fseek(textFile, 0L, SEEK_SET);

    fread(fileCharacterBuffer, 1, fileSize, textFile);
}

测试文件:

3
112
REd
110
green

#5/09/2014
5087 - 5/6/2014

它的十六进制转储,表明其EOL为\ r \ n:

Its hex dump, which shows its EOLs are \r\n:

Offset(h) 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F

00000000  33 0D 0A 31 31 32 0D 0A 52 45 64 0D 0A 31 31 30  3..112..REd..110
00000010  0D 0A 67 72 65 65 6E 0D 0A 0D 0A 23 35 2F 30 39  ..green....#5/09
00000020  2F 32 30 31 34 0D 0A 35 30 38 37 20 2D 20 35 2F  /2014..5087 - 5/
00000030  36 2F 32 30 31 34 0D 0A                          6/2014..

读取之后,GDB将fileCharacterBuffer打印为:

After the fread, GDB prints fileCharacterBuffer as:

"3\n112\nREd\n110\ngreen\n\n#5/09/2014\n5087 - 5/6/2014\n", '\000' <repeats 51 times>

仅带有\ n的存在.什么?

With only the \n's present. What?

推荐答案

您将看到文本模式"的效果,其中行尾从Windows转换为Unix,也称为C换行符.

You are seeing the effects of "text mode" where line endings are being converted from Windows to Unix aka C newlines.

您需要以二进制模式打开文件,这意味着在fopen标志中添加"b".看起来像textFile = fopen("./Test.txt", "rb+")

You need to open the file in binary mode which means adding a "b" to the fopen flags. It would look like textFile = fopen("./Test.txt", "rb+")

此外,我不确定我为什么会在读取文件之前得到文件的长度.

Also, I am not sure I understand why you get the length of the file before reading it.

只需阅读即可.查看fread的返回值以了解您阅读了多少内容.如果您将size设置为1,则返回值将是读取的字节数.

Just read it. Look at the return value of fread to see how much you read. If you use a size of 1 the return value will be the number of bytes read.

赞:

fileSize = fread(fileCharacterBuffer, 1, sizeof(fileCharacterBuffer), textFile);

这篇关于难道在C中放回车符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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