简体   繁体   English

如何修复代码以打开代码块中命令提示符中传递的文件

[英]How to fix code to open files passed in the command prompt in codeblocks

I'm trying to pass the names of the arguments to be readen in codeblocks through set program arguments.我正在尝试通过设置程序 arguments 传递 arguments 的名称以在代码块中读取。 When I open them directly, I use当我直接打开它们时,我使用

    FILE * file_1 = fopen("file31.ll", "r");
    FILE * file_2 = fopen("file32.ll", "r");

And it works, cause file31 and file32 are in the same paste as the file.它可以工作,因为 file31 和 file32 与文件在同一个粘贴中。 However, when I create a project (and put the files inside its paste), I try to write file31.ll and file32.ll in the arguments and it doesn't work.但是,当我创建一个项目(并将文件放在其粘贴中)时,我尝试在 arguments 中写入 file31.ll 和 file32.ll 并且它不起作用。 When compilling, the program warns that the files couldn't be open because the directory wasn't found ("error opening the file: no such a file or directory").编译时,程序警告无法打开文件,因为找不到目录(“打开文件时出错:没有这样的文件或目录”)。 I've also tried writing "file31" and "file32", and also copied the address in Windows like: C:\Users...\opening_files\file31 where opening_files is the name of the project我也尝试过编写“file31”和“file32”,并且还复制了 Windows 中的地址,例如:C:\Users...\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");
    }

I tried to read some other posts about this online but I haven't understand them very well, cause I'm pretty new to programming.我试图在网上阅读其他一些关于此的帖子,但我不太了解它们,因为我对编程很陌生。

The indexing of the argv[] is incorrect. argv[] 的索引不正确。 The argv[1] store the file_1 path and the argv[2] store the file_2 path. argv[1] 存储 file_1 路径, argv[2] 存储 file_2 路径。

FILE * file_1 = fopen(argv[1], "r");
FILE * file_2 = fopen(argv[2], "r");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM