【发布时间】:2016-03-06 13:14:19
【问题描述】:
我正在编写一个程序来替换 position % step = 0 所在的每个字符
作为命令行参数,我给出了1. file2. character 和3. step。我只能使用系统调用。这是我的主要功能:
int main(int argc, char **argv){
assert(argc == 4);
int fdInput = open(argv[1], O_WRONLY);
if(fdInput == -1)
fatalError("Error opening input file.\n");
char c[1];
c[0] = argv[2][0];
unsigned step = atoi(argv[3]);
int fileSize;
if((fileSize = lseek(fdInput,0,SEEK_END)) < 0)
fatalError("Lseek error: Determining file size\n");
if(lseek(fdInput,0,SEEK_SET) == -1)
fatalError("Lseek error: Returning to the beginning\n");
int i;
for(i = 0; i*step < fileSize; i++)
if(step - 1 > 0){
if(lseek(fdInput, i*step - 1, SEEK_SET) == -1)
fatalError("Lseek error: Within loop\n");
if(write(fdInput, c, 1) != 1)
fatalError("Writing error\n");
}
else {
if(write(fdInput, c, 1) != 1)
fatalError("Writing error.\n");
}
close(fdInput);
return 0;
}
示例:
input.txt:123456789
./output input.txt x 3 将返回 12x45x78x
问题:由于某种原因,当我第一次编译和执行时,一切正常!但是:当我第二次执行它时,它不会工作。当我尝试cat/less input.txt 它告诉我文件是二进制文件。
-
echo "123456789" > input.txt-> 创建.txt文件 -
./output input.txt x 3->12x45x78x -
./output input.txt x 3-> 不会工作(程序已完成),但是: -
less input.txt->input.txt" may be a binary file. See it anyway?
文件如何是二进制的?它应该是纯文本文件。我在这里做错了什么?我对open 做错了吗?
【问题讨论】:
-
我注意到的第一件事是,对我来说,即使是第一次执行也不能正常工作。文件似乎充满了大量的空字符(但替换的字符串看起来很好)。我会继续调查。
-
哇,我意识到你正在使用这段代码生成 4GB 稀疏文件。
-
在循环中的第一个 lseek 中,您会进行巨大的跳跃: lseek(3, 4294967295, SEEK_SET) = 4294967295 write(3, "x", 1) = 1
标签: c data-conversion