【发布时间】:2020-03-11 18:17:33
【问题描述】:
我正在尝试通过设置程序参数传递要在代码块中读取的参数名称。当我直接打开它们时,我使用
FILE * file_1 = fopen("file31.ll", "r");
FILE * file_2 = fopen("file32.ll", "r");
它可以工作,因为 file31 和 file32 与文件在同一个粘贴中。但是,当我创建一个项目(并将文件放在其粘贴中)时,我尝试在参数中写入 file31.ll 和 file32.ll 并且它不起作用。编译时,程序警告无法打开文件,因为找不到目录(“打开文件时出错:没有这样的文件或目录”)。我也试过写“file31”和“file32”,还复制了Windows中的地址,如: C:\用户...\opening_files\file31 其中 opening_files 是项目的名称
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "LCS.h"
int main(int argc, char * argv[])
{
if (argc < 3) {
printf("Incorret number of arguments!\n");
exit(1);
}
//I print argc and argv to test if the arguments are being passed correctly
printf("argc = %d\n", argc);
for (int i=1; i<argc; i++) {
fputs(argv[i], stdout);
printf("\n");
}
//They are printed correctly
//However, when trying to open the files, the program warns that the
//directories weren't found
//Opening the files
FILE * file_1 = fopen(argv[2], "r");
FILE * file_2 = fopen(argv[3], "r");
if (file_1 == NULL || file_2 == NULL)
{
perror("Error opening file\n");
}
我尝试在网上阅读其他一些关于此的帖子,但我不太了解它们,因为我对编程很陌生。
【问题讨论】:
-
更好的错误消息将帮助您确定错误。给出您要打开的文件的名称:
if( (file_1=fopen(argv[2], "r")) == NULL ) {perror(argv[2]); exit(EXIT_FAILURE);} -
它打印:打开文件时出错:没有这样的文件或目录
-
我的意思是“打开文件时出错”比给出使用的路径有用得多。此外,您需要立即检查。如果file_1 无法打开(例如权限被拒绝),那么errno 将不会反映发生的错误,并且perror 生成的消息将不准确。 (例如,第二个 fopen 可能成功并将 errno 设置为 0)