我的作业要求我使用缓冲的i / o复制文件。它有多个要求:
我遇到的问题是六号,我环顾四周,无法弄清楚这一点。我试过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);
}
答案 0 :(得分:0)
有天真的方式:
if(buffer[0] == 'r' && buffer[1] == 'w'
&& buffer[2] == 'x' && buffer[3] == 'r') {
//do something
}
但请查看strncmp(),您可以将其用于比较字符串的各个部分。
请记住首先检查您是否已将至少4个字符读入缓冲区。例如如果文件长度为21个字节,那么你的2. fread可能只读取1个字符,你不应该与缓冲区中的其他3个字符进行比较。
如果您打印出缓冲区,例如printf或puts或任何其他需要字符串的函数,缓冲区需要以'\ 0'字节结束,否则字符串函数不知道何时停止。
答案 1 :(得分:0)
我首先回答你实际问过的问题:memcmp是比较两个缓冲区的好方法。一些警告:
例如,如果你想查看缓冲区是否等于字符串“rwxw”,你可以编写
if (readresult >= strlen("rwxw") && !memcmp(buffer, "rwxw", strlen("rwxw"))) {
// buffer match occurred!
}
我个人会使用“#define”或const char来确保该字符串出现的三个地方实际上是相同的字符串。例如:
#define MATCH_STRING "rwxw"
if (readresult >= strlen(MATCH_STRING) && !memcmp(buffer, MATCH_STRING, strlen(MATCH_STRING))) {
// buffer match occurred!
}
但是,您的代码还有其他一些问题。一个是你需要一个循环,它不断地从输入文件中读取并从输出文件中写入,直到输入用完为止。例如,沿着
的路线while (true) {
readResult = fread(buffer, 20, 1, readfile);
if (readResult == 0) {
// end of file
break;
}
// put your check for the "rwxr" string here!
writeResult = fwrite(buffer, readResult, 1, writefile);
if (writeResult != readREsult) {
printf("error\n");
}
}
最后,你有一个可能被称为“风格”的错误。程序中有两种情况:指定的文件名和默认文件名。这两种情况共享很多代码,但是你做了剪切和粘贴。这使得代码更难理解,并且如果将来发生更改,则更容易出现错误。如果你正在剪切和粘贴代码,那么你做错了!请考虑这样的事情,它最大化共享代码路径:
char *outFileName;
if (argc == 3) {
outFileName = argv[2];
} else {
outFileName = "prog1.out";
}
writefile = fopen(outFileName, "w");
if (!writefile) {
printf("Unable to open file %s.\n", writeFileName);
exit(1);
}