在C中获取换行符的隐藏字符

问题描述 投票:-4回答:1

我有要做的工作,需要做一个linux2dos函数。

基本上,我必须找到所有换行符(0X0A)并在其前面放回车符(0X0D)。

由于LF和CR隐藏在文件中,所以我真的不知道如何使用它们。

我认为fgetc不能胜任,对吧?

谢谢!

c carriage-return linefeed
1个回答
0
投票

您是否正在从文本文件中读取数据?在嵌入式平台上吗?如果从所有数据均为ASCII的文本文件中读取,则可以一次读取几个字节并检查换行符'\ n'(0X0A)。

void find(void)
{
    unsigned char buffer[256];
    unsigned char  newBuffer[sizeof(buffer)+1];
    unsigned char  *pChr;//pointer to where the \n is
    unsigned short location = 0, bytesRead;

    //Ex. 
    FileRead(buffer, sizeof(buffer), &bytesRead);
    pChr = strchr(buffer, '\n');

    if (NULL != pChr)
    {
        location = (pChar - &buffer[0])  - 1;
        //get where the \n is and minus 1 to get the index before it

        memcpy(newBuffer, buffer, location); //copy bytes to spot before \n
        newBuffer[location] = 0X0D; // insert '\r'
        memcpy(&newBuffer[location +1], pChr+ location, bytesRead - location); //copy the rest of the array   
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.