调试没有错误或警告

时间:2016-07-23 12:23:11

标签: c gcc

以下代码编译时没有错误或警告,我也可以执行该程序,它将按预期运行,因为它将在预期的位置返回错误消息,例如,为不存在的文件提供参数。这让我知道代码工作到第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

testtest2所以它看起来像

"ting"
"test"
"123"

谢谢,不知道要提供多少信息。

1 个答案:

答案 0 :(得分:3)

您的代码存在许多问题,编译时启用的所有警告都会发现其中的一些:

  • 在头文件中声明全局变量是一种很好的做法,但不是在那里定义它们。 extern关键字用于声明。这些定义属于C文件。在这种情况下,fpfp1line等变量应定义为局部变量,而不是全局变量。
  • 输出文件argv[2]应该以{{1​​}}模式打开,"w"用于更新模式,如果文件不存在则会失败。更新模式非常棘手且令人困惑,请避免使用它。
  • 不要使用"r+"关键字,现在它已经过时,因为编译器足够聪明,可以确定如何最好地使用寄存器。
  • 您的register循环将只读取输入文件中的2行,将第一行存储到while数组中并丢弃第二行。
  • line语句退出程序,不执行输出,函数中的其余语句被完全忽略(-Wall可能已发现此错误)。

您可以通过以下方式简化问题:您希望在每行的开头和每行末尾的return (i);之前输出"。您不需要在内存中缓冲行,这会对行长度施加限制。只要你开始一行,就在结束一行之前输出'\n'

"