c - 无法执行C代码

标签 c

int  main(int argc, char *argv[])
    {
        FILE *fp, *fp1, *fp2;
        char line[200], temp[50], prev_het[5], curr_het[5], pdb_id[5], conneected_residues[10000], pres_name[4], pres_no[9], curr_temp[5], lig_atom[6], is_reesidue_present[10], curr_het_num[9], prev_het_num[9], chain_prot[2], chain_lig[2]];
        p_atom *front, *present;

        double het_x, het_y, het_z, dist;
        int flag, comma_indicator, no_of_het_atoms = 0, nmr_flag = 0, prot_ccount =0, connected_het = 0, connected_prot = 0, atom_flag = 0;

        front = present = NULL;
        prev_het[0] = curr_het[0] = '\0';
        fp = fopen(argv[1], "r");

        if(fp == NULL)if(fp == NULL)
        {
            printf("Error in opening %s file",argv[1]);
            exit (0);
        }

大家好, 这是我的 C 代码的一部分。我无法理解如何执行此代码,因为它给出了如下所述的错误:

“打开(空)文件时出错”

谁能帮帮我

最佳答案

如果您收到错误:

Error in opening (null) file

那么通常是因为您提供了一个指向 fopen() 的 NULL 指针,但由于这在技术上是未定义的行为,所以对于实际情况如何,所有的赌注都将被取消。发生。

由于 fopen() 的参数是 argv[1],几乎可以肯定是因为您没有使用参数运行程序。

换句话说,您正在执行 myprog 而不是 myprog myfile,这意味着第一个参数将为 NULL (根据需要按标准)。

无论如何,您应该进行防御性编程来捕获该特定问题,例如:

if (argc < 2) {
    fprintf (stderr, "Not enough parameters\n");
    return 1;
}

FILE *fp = fopen (argv[1]);
if (fp == NULL) {
    fprintf (stderr, "Cannot open file\n");
    return 1;
}
:
// Can probably assume it's okay now.
:
fclose (fp);
return 0;
<小时/>

您可能还想了解:

if(fp == NULL)if(fp == NULL)

我非常确定(除非您使用线程),如果第一次为 NULL,那么第二次也将是 NULL :- )

关于c - 无法执行C代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34487721/

相关文章:

c - 时间结构使用

c - 为什么第二次调用 RasGetEntryProperties() 返回正在进行的重叠 I/O 操作?

c - 如何在 C 中通过 HTTP 写入图像?

c - 错误在 `./a.out' : free(): invalid next size (normal) while freeing dynamically allocated 2D array of struct

c++ - 递归调用函数时变量的值

c - 使用 C 中的递归计算算术表达式

c - 将字符数组中的字符放入字符串中,直到找到特定字符

c - 为 C 寻找一个好的 GUI 库

c - C中的内存泄漏,函数内部的malloc

c - memcpy() 不会停止复制