以下代码编译时没有错误或警告,我也可以执行该程序,它将按预期运行,因为它将在预期的位置返回错误消息,例如,为不存在的文件提供参数。这让我知道代码工作到第28行(关闭!fpc部分)
意味着
必须存在问题register int ch, i;
向下
return (1);
前
printf("\"%s\"\n",line);\
程序应该获取程序名称本身的命令行参数和两个文件名,然后打开这两个文件,然后在添加时将第一个文件中的字符串复制到第二个文件的最大长度"
到新文件中字符串的开头和结尾。
我的代码是
fgetline.c
#include "fgetline.h"
int main(int argc, char *argv[]) {
if (argc != 3) {
printf("usage: enquote filetocopy filetowrite \n");
exit(1);
}
fp = fopen(argv[1], "r");
if (!fp) {
printf("Couldn't open copy file: (%d) %s\n", errno, strerror(errno));
return -1;
}
fpc = fopen(argv[2], "r+");
if (!fpc) {
printf("Couldn't open write file: (%d) %s\n", errno, strerror(errno));
return -1;
}
register int ch, i;
ch = getc(fp);
if (ch == EOF)
return -1;
i = 0;
while (ch != '\n' && ch != EOF && i < max) {
line[i++] = ch;
ch = getc(fp);
}
line[i] = '\0';
while (ch != '\n' && ch != EOF) {
ch = getc(fp);
i++;
}
return(i);
printf("\"%s\"\n",line);
fclose(fp);
fclose(fpc);
return 0;
}
fgetline.h
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
int fgetline(FILE *fp, char *line, int max);
FILE *fp, *fpc;
#define max 30
char line[max + 1];
我正在编译
debian:~/uni/Ass0$ gcc fgetline.c -Wall -o enquote
debian:~/uni/Ass0$ cd /
我做的测试是
debian:~/uni/Ass0$ ./enquote
usage: enquote filetocopy filetowrite
debian:~/uni/Ass0$ ./enquote test
usage: enquote filetocopy filetowrite
debian:~/uni/Ass0$ ./enquote test frog
Couldn't open write file: (2) No such file or directory
debian:~/uni/Ass0$ ./enquote monkey frog
Couldn't open copy file: (2) No such file or directory
debian:~/uni/Ass0$ cat test
ting
test
123
tim@debian:~/uni/Ass0$ cat test2
tim@debian:~/uni/Ass0$ ./enquote test test2
tim@debian:~/uni/Ass0$ cat test2
预期结果将是我运行./enquote test test2,将复制
ting
test
123
从test
到test2
所以它看起来像
"ting"
"test"
"123"
谢谢,不知道要提供多少信息。
答案 0 :(得分:3)
您的代码存在许多问题,编译时启用的所有警告都会发现其中的一些:
extern
关键字用于声明。这些定义属于C文件。在这种情况下,fp
,fp1
,line
等变量应定义为局部变量,而不是全局变量。argv[2]
应该以{{1}}模式打开,"w"
用于更新模式,如果文件不存在则会失败。更新模式非常棘手且令人困惑,请避免使用它。"r+"
关键字,现在它已经过时,因为编译器足够聪明,可以确定如何最好地使用寄存器。register
循环将只读取输入文件中的2行,将第一行存储到while
数组中并丢弃第二行。line
语句退出程序,不执行输出,函数中的其余语句被完全忽略(-Wall可能已发现此错误)。您可以通过以下方式简化问题:您希望在每行的开头和每行末尾的return (i);
之前输出"
。您不需要在内存中缓冲行,这会对行长度施加限制。只要你开始一行,就在结束一行之前输出'\n'
:
"