gpt4 book ai didi

C 使用文件作为参数

转载 作者:行者123 更新时间:2023-11-30 20:13:33 26 4
gpt4 key购买 nike

我遇到的问题是,每当我运行代码时,在我将文件名作为参数传递到程序之前,我都会得到 myfile 的 Null 值,并且我不确定为什么非常感谢任何帮助。

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
FILE* myFile; // file pointer
myFile = fopen(argv[1] , "r"); //open file
if(myFile==NULL)
{
printf("Can't Open FIle.\n"); // if file doesn't exist then exit
exit(0);
}

int A[10000]={0};
int B[10000]={0};
double C[10000]={0};
int N,M;
int i=0;

fscanf (myFile, "%d", &N); //input N from file
printf("%d\n",N);
if(N>100)
{
exit(0); // if N>100 then exit
}
while (!feof (myFile)) // loop until file pointer reaches to the end of file
{
fscanf (myFile, "%d", &A[i]); //input source
fscanf (myFile, "%d", &B[i]); // input destination
fscanf (myFile, "%lf", &C[i]); // input time
i++;
}
fclose (myFile); //close file

M=i; // number of lines = M

for (i = 0; i < M; i++)
{
if(A[i]==0) //end of output
break;
else
{
printf("%d %d %lf:\n",A[i],B[i],C[i]); //print source, destination and time
if(A[i]>=1&&A[i]<=N)
{
if(B[i]>=1&&B[i]<=N)
{
if(A[i]==B[i])
{
printf("Error:Source city is the same as destination city.\n"); //same source and destination error:condition
}
else
{
if(C[i]<0)
{
printf("Error:Invalid Time.\n"); //invalid time
}
else
{
//
}
}
}
else
{
printf("Error: Invalid destination city.\n"); //invalid destination condition
}
}
else
{
printf("Error: Invalid source city.\n"); //invalid source condition
}
}
}

return 0;
}

最佳答案

如果不将文件名作为参数传递给程序,则 argv[1] 的内容未定义。

由于当程序尝试打开文件时,argv[1] 中可能存在任何内容,因此最有可能的情况是不存在具有该名称的文件,因此 fopen( ) 返回NULL

您不应该在没有检查是否提供命令行参数的情况下尝试访问命令行参数,对于该检查 argc,如果您只期望 1 个参数,那么将进行简单的检查

char filename[256]; /* the size should be reasonable
* can be PATH_MAX or MAX_PATH,
* depending on whether it's Windows
* or not
*/
if (argc < 2)
{
size_t length;

fprintf(stdout, "Error: %s program expects one argument\n", argv[0]);
fprintf(stdout, "Please input the file name: ");
if (fgets(filename, sizeof(filename), stdin) == NULL)
{
fprintf(stdout, "Error: unexpected error\n");
return -1;
}
length = strlen(filename);
if (length == 0)
{
fprintf(stdout, "Error: the provided file name is invalid.\n");
return -1;
}
if (filename[length - 1] == '\n')
filename[length - 1] = 0;
}
else
strcpy(filename, argv[1]);

关于C 使用文件作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29735251/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com