You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言技术问询:如何将命令行缩写参数补全为完整归档文件名并打开

Hey there! Let's walk through fixing your code so it properly appends the .csv suffix to your command-line arguments and opens the correct file.

First, let's spot the critical issues in your original code:

  • You're using a FILE* pointer (csv) as the target for sprintf—that's a big mistake! FILE* points to file metadata, not a string buffer, so writing to it will cause undefined behavior (crashes, garbage data, etc.).
  • Even if that part worked, you're still trying to open argv[1] (the original "btc" argument) instead of the suffixed filename you attempted to create.

Here's a corrected version of your code, with explanations of the key changes:

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

int main(int argc, char *argv[]) {
    // Make sure we have at least one filename prefix argument
    if (argc < 2) {
        printf("Usage: %s <filename_prefix>\n", argv[0]);
        exit(1);
    }

    // Process each command-line argument
    for (int i = 1; i < argc; i++) {
        // Calculate the size needed for the full filename: original length + ".csv" (4 chars) + null terminator
        size_t filename_length = strlen(argv[i]) + 5;
        // Allocate memory for the full filename (safe for long arguments)
        char *full_filename = malloc(filename_length);
        
        if (!full_filename) {
            perror("Failed to allocate memory");
            exit(1);
        }

        // Safely append the .csv suffix to the argument
        snprintf(full_filename, filename_length, "%s.csv", argv[i]);

        // Try to open the suffixed file
        FILE *csv_file = fopen(full_filename, "r");
        if (csv_file == NULL) {
            printf("Could not find or open file: %s\n", full_filename);
            free(full_filename); // Don't forget to free memory before moving on
            continue; // Skip to the next argument if this one fails
        }

        // If we got here, the file opened successfully
        printf("Successfully opened %s\n", full_filename);

        // Add your file processing logic here (reading data, parsing CSV, etc.)

        // Clean up: close the file and free the allocated memory
        fclose(csv_file);
        free(full_filename);
    }

    return 0;
}

Key improvements:

  • Proper string storage: We use a dynamically allocated char* (or you could use a fixed-size char array like char full_filename[256]; for simpler cases) to hold the suffixed filename instead of misusing a FILE*.
  • Safe string concatenation: snprintf replaces sprintf to prevent buffer overflow by specifying the maximum number of characters to write.
  • Use the correct filename: We pass full_filename (the suffixed version) to fopen instead of the original argv[i].
  • Memory safety: We check if malloc succeeds, and we always free the allocated memory after use to avoid leaks.
  • Argument validation: We first confirm the user provided at least one argument, so we don't try to access argv[1] when it doesn't exist.

If you prefer a simpler fixed-size buffer (good for short filenames), you could replace the dynamic allocation part with:

char full_filename[256];
snprintf(full_filename, sizeof(full_filename), "%s.csv", argv[i]);

Just note that if argv[i] is longer than ~250 characters, this will truncate the filename—dynamic allocation is safer for arbitrary-length inputs.

内容的提问来源于stack exchange,提问作者Andre

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 12:15:58