我对 C 编程语言相当陌生。我正在编写一个程序,最终将从用户输入的目录中读取 mp3 文件,并利用 id3 中的元数据将 mp3 分类到艺术家/专辑文件夹中。我正在使用 system() 函数调用访问用户的目录,并生成一个包含该目录中所有 mp3 的 .txt 文件。但是,我在尝试访问第一个 mp3 文件时遇到了问题。我正在构建 mp3 文件的路径,但该文件无法打开。当我对路径进行硬编码时,文件确实打开了。
#include <stdio.h>
#include <string.h>
struct FILE_head
{
char file_id[3];
char version[2];
char flags;
char size[4];
};
int main()
{
//declare vars
char cd[1200];
char mp3[200];
char dir[1000];
char mp3_path[1200];
FILE *list_file;
FILE *mp3_file;
struct FILE_head id3;
char dir_cmd[1300] = "dir ";
char find_cmd[100] = "/b | find \".mp3\" > \"mp3List.txt\"";
int dir_len;
int amt_read;
//main code
while(1)
{
cd[0]='c';
cd[1]='d';
cd[2]=' ';
cd[3]='\0';
printf("Enter the directory where mp3's are located:");
scanf("%s", dir);
strcat(cd, dir);
if(system(cd) == 0) //if directory is valid, break. otherwise stay in loop/reprompt
break;
printf("Valid directory Ex--> c:\\users\\username\\music\n");
}
//build cmd statement
strcat(dir_cmd, dir);
strcat(dir_cmd, find_cmd);
system(dir_cmd);
dir_len = strlen(dir);
strcpy(mp3_path, dir);
printf("%s\n", mp3_path);
list_file = fopen("mp3List.txt", "rb");
if(list_file != NULL)
{
while(fgets(mp3, sizeof(mp3), list_file))
{
printf("%s", mp3);
strcat(mp3_path, mp3);
printf("%s\n", mp3_path);
mp3_path[strlen(mp3_path)-1] = '\0';
mp3_file = fopen(mp3_path, "rb");
if(mp3_file != NULL)
{
printf("in this loop");
fread(&id3, sizeof(id3), 1, mp3_file);
printf("%s\n", id3.file_id);
}
}
}
return 0;
}
这是我第一次发帖,所以如果有更多信息对您有帮助,请告诉我。我意识到可能有“更好”的方式来访问目录,但我不想使用任何不在 C 标准库中的函数。
这是我的输出:
C:\Users\Mitchell\Projects>mp3sort.exe Enter the directory where mp3's are located:c:\users\mitchell\projects\music_test\ c:\users\mitchell\projects\music_test\ 01 - Time to Pretend.mp3 c:\users\mitchell\projects\music_test\01 - Time to Pretend.mp3
01-all_that_remains-this_calling.mp3 01-all_that_remains-this_calling.mp3t\01 - Time to Pretend.mp3
07 Billy Joel - Everybody Loves You Now.mp3 07 Billy Joel - Everybody Loves You Now.mp3Time to Pretend.mp3
Tears for the Sheep.mp3 Tears for the Sheep.mp3dy Loves You Now.mp3Time to Pretend.mp3
C:\Users\Mitchell\Projects>
我知道我当前构建的第一个文件之后的所有文件都不正确,但我只是专注于让第一个 mp3_path 正常工作。我通过以下方式删除了换行符:mp3_path[strlen(mp3_path)-1] = '\0';
最佳答案
system()
在子进程中执行提供的命令。当您执行 system ("cd somedir")
时,cd somedir
在子进程中执行,因此您进程的工作目录保持不变。
如果你想改变你的进程工作目录,使用chdir()
(或 _chdir()
,或者 SetCurrentDirectory
如果您想使用 Windows API)函数。
或者,您可以通过将目录添加到文件名来避免更改工作目录。
关于C编程——从特定的windows目录打开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26210827/