C: 如何使用主 argv 的参数打开文件?

C: How to open a file using the parameter to main argv?

我一直在尝试使用 char** argv 参数打开文件。但不幸的是,当我以这种格式传递文件路径时,我遇到了读取文件路径的问题:program.exe Function SourceFile DestFile。

我使用 notepad++ 编写代码,使用 GCC 编译并将参数传递给函数

更新:我修复了代码,现在应该可以工作了...

#include <stdio.h>
#include <string.h>

void textCopy(FILE* sourceFile, FILE* destinationFile);
void binaryCopy(FILE* sourceFile, FILE* destinationFile);

int main(int argc, char** argv)
{
    printf(argv[2]);
    if ((strcmp(argv[1], "textCopy") != 0 && strcmp(argv[1], "binaryCopy") != 0))
    {
        printf("Error: Function Doesn't Exist");
        return 1;
    }
    FILE* sourceFile = fopen(argv[2], "r");
    if (sourceFile == NULL)
    {
        printf("Error: Source File Doesn't Exist");
        return 1;
    }
    FILE* destinationFile = fopen(argv[3], "w");
    if (destinationFile == NULL)
    {
        printf("Error: Destination File Doesn't Exist");
    }
    if (strcmp(argv[1], "textCopy") == 0)
    {
        textCopy(sourceFile, destinationFile);
    }
    else
    {
        binaryCopy(sourceFile, destinationFile);
    }
    getchar();
    return 0;
}

void textCopy(FILE* sourceFile, FILE* destinationFile)
{
    char letter = 0;
    while (letter != EOF)
    {
        letter = fgetc(sourceFile);
        fputc(letter, destinationFile);
    }
}

void binaryCopy(FILE* sourceFile, FILE* destinationFile)
{
    printf("Ignore");
}

我在互联网上搜索了解决方案,但似乎无济于事,当我阅读 argv[2] 时,我只得到路径中的 C:\ 部分,而不是整个路径...

谢谢!

本着以下精神尝试一些事情:

program.exe textCopy "C:\path to\the source file\my source file.ext" "C:\path to\the destination file\my destination file.ext"

您缺少的是命令行中文件路径周围的双引号。