【发布时间】:2023-03-29 14:37:01
【问题描述】:
我正在编写一个简单的程序来翻转文件中的所有位,但现在它只处理前 1000 个字节,直到我得到那么多工作。为什么我对 read() 的调用会忽略 \r 字符?当我在仅包含 \r\n\r\n 的文件上运行此代码时,读取调用返回 2 并且缓冲区包含 \n\n。 \r 字符被完全忽略。我在 Windows 上运行它(这在 Linux 机器上甚至都不是问题)
为什么 read(2) 在找到 \r 字符时会跳过它?或者这就是正在发生的事情?
编辑:结论是 Windows 默认以“文本”模式打开文件,而不是“二进制”模式。因此,在调用 open 时,我们必须指定 O_BINARY 作为模式。
谢谢,代码如下。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/stat.h>
#include <fcntl.h>
void invertBytes(size_t amount, char* buffer);
int main(int argv, char** argc)
{
int fileCount = 1;
char* fileName;
int fd = 0;
size_t bufSize = 1000;
size_t amountRead = 0;
char* text;
int offset = 0;
if(argv <= 1)
{
printf("Usages: encode [filenames...]\n");
return 0;
}
text = (char *)malloc(sizeof(char) * bufSize);
for(fileCount = 1; fileCount < argv; fileCount++)
{
fileName = argc[fileCount];
fd = open(fileName, O_RDWR);
printf("fd: %d\n", fd);
amountRead = read(fd, (void *)text, bufSize);
printf("Amount read: %d\n", amountRead);
invertBytes(amountRead, text);
offset = (int)lseek(fd, 0, SEEK_SET);
printf("Lseek to %d\n", offset);
offset = write(fd, text, amountRead);
printf("write returned %d\n", offset);
close(fd);
}
return 0;
}
void invertBytes(size_t amount, char* buffer)
{
int byteCount = 0;
printf("amount: %d\n", amount);
for(byteCount = 0; byteCount < amount; byteCount++)
{
printf("%x, ", buffer[byteCount]);
buffer[byteCount] = ~buffer[byteCount];
printf("%x\r\n", buffer[byteCount]);
}
printf("byteCount: %d\n", byteCount);
}
【问题讨论】:
-
你使用的是什么环境?
open和read不是 Windows 原生的。 -
这一切现在都是在 windows xp 上完成的。我从命令行编译它。
-
是的,但是您使用的是哪个开发环境?
-
哦,哈哈,我不是。我正在使用记事本++。
-
您确定使用的是编译器和一个或多个运行时库吗?