首页 > 解决方案 > 为什么我在 VSCode 中的文件 I/O 不能正常工作?

问题描述

为更清晰而编辑。

目前在 C 中使用 VSCode 处理文件时遇到问题。

在 CS50 中,我们使用基于浏览器的 CS50 IDE 来回答问题集。我尝试使用 Visual Studio Code 来编译相同的代码gcc test.c -o test,并且确实如此。但问题是当我运行时./test card.raw,它没有按预期运行。card.raw是包含 50.jpg张图像的输入文件,下面将详细介绍。

CS50 IDE 使用

clang -ggdb3 -O0 -std=c11 -Wall -Werror -Wextra -Wno-sign-compare -Wno-unused-parameter -Wno-unused-variable -Wshadow test.c -lcrypt -lcs50 -lm -o test,

但我不确定这是否有区别。代码在 CS50 IDE 和 VSCode 中相同,如下所示:

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

typedef uint8_t BYTE;
const int FAT = 512;

int main(int argc, char *argv[])
{
    // Check usage
    if (argc != 2)
    {
        printf("Usage: ./ filename.raw\n");
        return 1;
    }

    // Open file
    FILE *file = fopen(argv[1], "r");
    if (file == NULL)
    {
        printf("File could not be read.\n");
        return 1;
    }

    // Initializing a buffer
    BYTE buffer[FAT];

    // Counter for filename
    int counter = 0;

    // Pointer declaration for new images
    FILE *img = NULL;

    char *filename = malloc(8 * sizeof(char));

    while (fread(buffer, 1, FAT, file) != 0)
    {
        // Checks if JPEG
        if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
        {
            // Sets up the filename
            sprintf(filename, "%03i.jpg", counter);
            img = fopen(filename, "w");
            counter++;
        }
        
        if (img != NULL)
        {
            fwrite(buffer, 1, FAT, img);
        }
    }
    // Closes all opened files
    fclose(img);

    fclose(file);

    // Frees memory from malloc
    free(filename);

    return 0;
}

在这个特定的代码中,card.raw为我们提供了输入文件。它里面包含50个.jpg文件。所以,我希望有 50 个输出.jpg文件,命名为000.jpg,001.jpg等等,直到049.jpg可以像普通.jpg文件一样在视觉上进行检查。

它在 CS50 IDE 中运行良好。当我./test card.raw在 CS50 IDE 中运行时,它会.jpg按预期输出 50 个文件。但是在使用 VSCode 时,它​​只生成 1 个.jpg文件,名为000.jpg. 打开时,它说文件格式不受支持或已损坏。

test.c, test.exe,card.raw都在同一个目录中,就像在 CS50 IDE 中一样。

我还注意到 VSCode 中的编译代码使用.exe文件格式,如test.exe. .exe但是当我从 CS50 IDE 下载编译后的代码时,它不在test.

我想我在这里想要实现的是,当我慢慢移除 CS50 IDE 提供的“训练轮”时,我想更舒适地使用更流行的 IDE,如 VSCode 或 Atom。

标签: cvisual-studio-codefile-ioidecs50

解决方案


推荐阅读