将行附加到 C 中的特定文件扩展名
Append line to specific file extension in C
所以我一直在尝试制作一个工具来在具有特定扩展名的文件中创建文本,但是 运行 遇到了一个问题,想知道如何解决它。
代码如下:
if (d) {
while (((dir = readdir(d)) != NULL)) { // if directory exists
ext = strchr(dir->d_name, '.'); // const char
entry_file = fopen(dir->d_name, "a");
if (strcat(dir->d_name, ".lua")) { // if the file's extension is lua, then apply the changes.
//fopen(dir->d_name, "r");
printf(dir->d_name);
fprintf(entry_file, "filename = ", sentence);
fclose(entry_file);
}
}
closedir(d); // close directory
}
您没有将变量 sentence
插入到文件中。您需要 %s
来告诉 fprintf 将下一个参数实际包含到您写入文件的字符串中。
file = fopen(file_name, "a");
fprintf(file, "%s", text_to_append);
fclose(file);
如评论中所述,您还需要更改 printf 以使用格式说明符。进行这些更改后,您的代码应如下所示。
if (d) {
while (((dir = readdir(d)) != NULL)) {
ext = strchr(dir->d_name, '.');
if ((ext != NULL) && (strcmp(ext, ".lua") == 0)) {
printf("%s", dir->d_name);
entry_file = fopen(dir->d_name, "a");
fprintf(entry_file, "filename = %s", sentence);
fclose(entry_file);
}
}
closedir(d);
}
有关不同格式说明符的详细信息,请参阅 format string specifications。
所以我一直在尝试制作一个工具来在具有特定扩展名的文件中创建文本,但是 运行 遇到了一个问题,想知道如何解决它。
代码如下:
if (d) {
while (((dir = readdir(d)) != NULL)) { // if directory exists
ext = strchr(dir->d_name, '.'); // const char
entry_file = fopen(dir->d_name, "a");
if (strcat(dir->d_name, ".lua")) { // if the file's extension is lua, then apply the changes.
//fopen(dir->d_name, "r");
printf(dir->d_name);
fprintf(entry_file, "filename = ", sentence);
fclose(entry_file);
}
}
closedir(d); // close directory
}
您没有将变量 sentence
插入到文件中。您需要 %s
来告诉 fprintf 将下一个参数实际包含到您写入文件的字符串中。
file = fopen(file_name, "a");
fprintf(file, "%s", text_to_append);
fclose(file);
如评论中所述,您还需要更改 printf 以使用格式说明符。进行这些更改后,您的代码应如下所示。
if (d) {
while (((dir = readdir(d)) != NULL)) {
ext = strchr(dir->d_name, '.');
if ((ext != NULL) && (strcmp(ext, ".lua") == 0)) {
printf("%s", dir->d_name);
entry_file = fopen(dir->d_name, "a");
fprintf(entry_file, "filename = %s", sentence);
fclose(entry_file);
}
}
closedir(d);
}
有关不同格式说明符的详细信息,请参阅 format string specifications。