我有一个任务,要求我使用缓冲的I/O复制文件。它有多种要求:寻找一个字符串复制到缓冲区
- 取一个参数和一个可选的第二
- 打开第一读取
- 打开第二个写
- 参数如果没有第二个参数创建一个名为PROG1新文件.OUT
- 使用的20个字节
- 缓冲器大小在复制文件时,打印任何缓冲开始以字符“rwxr”
- CLO在退出之前查看所有打开的文件。
我遇到的问题是数字6,我环顾四周,无法弄清楚这一点。我尝试过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);
}
好的,我明白了。非常感谢你,我想我会尝试使用strncmp()。我仍然在努力尽可能多地学习C语言。 – sjhaw