【发布时间】:2011-10-15 00:36:44
【问题描述】:
我有一个任务要求我使用缓冲 i/o 复制文件。它有多个要求:
- 采用一个参数和一个可选的第二个参数
- 打开第一个参数进行读取
- 打开第二个写
- 如果没有第二个参数,则创建一个名为 prog1.out 的新文件
- 使用 20 字节大小的缓冲区
- 复制文件时,打印任何以字符“rwxr”开头的缓冲区
- 退出前关闭所有打开的文件。
我遇到的问题是六号,我环顾四周,无法弄清楚。我已经尝试过 memchr,但我认为我没有走在正确的轨道上。如果有人能帮助我朝着正确的方向前进,我将不胜感激。
这是我的代码:
# include <stdlib.h>
# include <stdio.h>
int main(int argc, char *argv[])
{
FILE *readfile, *writefile;
char buffer[1024];
int fileSize;
int readResult;
int writeResult;
// making sure arguments exist
if (argc < 2|| argc > 3){
printf("This program takes either 1 or 2 arguments.\n");
exit(1);
}
//Opening file for reading
readfile = fopen(argv[1], "r");
if (!readfile) {
printf("Unable to open file %s.\n", argv[1]);
exit(1);
}
//finding the file size
fseek (readfile, 0, SEEK_END);
fileSize = ftell (readfile);
fseek (readfile, 0, SEEK_SET);
// read the file
readResult = fread(buffer, 20, fileSize/20, readfile);
if (readResult == 0) {
printf("A read error occured.\n");
exit(1);
}
//check to see if there is a second parameter (argument)
if (argc == 3) {
writefile = fopen(argv[2], "w");
if (!writefile) {
printf("Unable to open file %s.\n", argv[2]);
exit(1);
}
writeResult = fwrite(buffer, 20, fileSize/20, writefile);
if (writeResult != readResult) {
printf("A write error occured.\n");
exit(1);
}
printf("File %s successfully copied to %s.\n", argv[1], argv[2]);
}
else {
writefile = fopen("program1.out", "w");
if (!writefile) {
printf("Unable to open file program1.out\n");
exit(1);
}
writeResult = fwrite(buffer, 20, fileSize/20, writefile);
if (writeResult != readResult) {
printf("A write error occured.\n");
exit(1);
}
printf("File %s successfully copied to %s.\n", argv[1], "program1.out
}
fclose(readfile);
fclose(writefile);
exit(0);
}
【问题讨论】: