C 使用命令行获取文件
我试图打开两个文件,但由于某种原因,fopen一直返回Null。我在mac上使用codelite。我将这两个文件放在同一个文件夹中,并将dictionary.txt和input.txt文件放在设置中的projects参数中。我还尝试使用完整路径并检查了文件的读取权限 这是我的密码:C 使用命令行获取文件,c,command-line-arguments,C,Command Line Arguments,我试图打开两个文件,但由于某种原因,fopen一直返回Null。我在mac上使用codelite。我将这两个文件放在同一个文件夹中,并将dictionary.txt和input.txt文件放在设置中的projects参数中。我还尝试使用完整路径并检查了文件的读取权限 这是我的密码: #include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[] ) { FILE *dict;
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[] ) {
FILE *dict;
FILE *input;
int x;
if ( argc < 3 ) /* argc should be 3 for correct execution*/
{
fprintf(stderr,"1 or 2 Files were missing.");
exit(1);
}
if ( argc > 3 ){
fprintf(stderr,"too many Arguments");
exit(1);
}
/* We assume argv[1] and agrv[2] are filenames to open*/
dict = fopen( argv[1], "r" );
input = fopen( argv[2], "r" );
/* fopen returns NULL on failure */
if ( dict == NULL ){
fprintf(stderr,"Could not open file: %s\n", argv[1] );
exit(1);
}
if ( input == NULL ){
fprintf(stderr,"Could not open file: %s\n", argv[2] );
exit(1);
}
/* Read one character at a time from file, stopping at EOF, which
indicates the end of the file. Note that the idiom of "assign
to a variable, check the value" used below works because
the assignment statement evaluates to the value assigned. */
while ( ( x = fgetc( input ) ) != EOF ) {
printf( "%c", x );
}
fclose( dict );
fclose( input );
return 0;
}
关于:
这两个文件都在同一个文件夹中
在IDE中工作时,您认为所在的文件夹通常不是您实际所在的文件夹
将以下行临时放置在干管的开始处:
看看它输出了什么。如果与文件所在的位置不同,则需要移动它们或更改在命令行上为程序提供的内容
您可能需要注意的其他事项是您必须具有读取权限的文件权限,并且file case Input.txt与Input.txt不同
如果这些建议都不能解决问题,您通常可以查看errno以了解具体问题是什么。在代码顶部包含errno'h并打印出errno变量
或者,在检查故障的if块中,将其更改为如下内容:
if ( dict == NULL ){
fprintf(stderr,"Could not open file: %s\n", argv[1] );
perror ("opening dict file");
exit(1);
}
确保运行该程序的用户具有文件的读取权限,并查看其是否使用完整路径可能该程序不是从您期望的目录运行的?我尝试使用完整路径,但仍然无效,我检查了读取权限您可以使用void perroconst char*s;而不是fprintf来显示详细错误消息。
if ( dict == NULL ){
fprintf(stderr,"Could not open file: %s\n", argv[1] );
perror ("opening dict file");
exit(1);
}