Home > Software engineering >  Append line to specific file extension in C
Append line to specific file extension in C

Time:12-31

So I have been trying to make a tool which creates text inside files with a specific extension, but ran into an issue and wonder how I can fix it.

Here is the code:

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
}

CodePudding user response:

You're not inserting the variable sentence into the file. You need the %s to tell fprintf to actually include the next argument into the string you're writing to the file.

file = fopen(file_name, "a");
fprintf(file, "%s", text_to_append);
fclose(file);

As noted in the comments, you need to change your printf to use the format specifier as well. Your code should look something like this after those changes.

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);
}

See format string specifications for more information about different format specifiers.

  • Related