我正在编写一个简单的程序来翻转文件中的所有位,但现在它只处理前 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);
}
最佳答案
fd = open(fileName, O_RDWR);
应该是
fd = open(fileName, O_RDWR | O_BINARY);
关于c - read(2) 如何与回车交互?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8764046/