c - 为什么我在 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。
解决方案
推荐阅读
- android - 将数据添加到 TableLayout 的新列中的现有行 - Kotlin
- elasticsearch - 模糊匹配失败但精确匹配通过
- node.js - 如何使用 node.js 8.10 创建一个 Alexa 技能,从我自己的数据库中给出答案
- python - 用 pandas 实现 count、groupby、np.repeat 和 agg 的问题
- java - Apache Commons Net FTPClient 默认使用被动模式还是主动模式?
- python - 语音 AI 帮助 Unicode 不可调用
- matlab - Matlab cftool - 使用百分比偏差作为标准进行拟合
- python - 导入导入另一个文件的文件时发现“未命名模块”
- django - 导入 django ModuleNotFoundError:安装 python 2 后没有名为“django”的模块
- ios - iOS 上的 Uber 深度链接取货位置问题