سؤال

Is it possible to pass the value of a variable inside the file name declared after the FILE construction in C?

My purpose is to have the value of the variable w printed in the file name in the following code snippet:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "nr.h"
#include "nrutil.h"
double h = 0.01;
double w = 5.0;
int main(void)
{
    FILE * fp = fopen("q1function_W_VALUEHERE.dat","w+"); 
/* The point I would like to have the value of w printed */
    for(i = 0; i < N; i++)
    {
        t[i] = i * h;
        y[i] = func(t[i]);
        fprintf(fp, "%f \t %f \n", t[i], y[i]); 
    }   
    fclose(fp);
    return 0;
}

int i = 42;
char fname[PATH_MAX];
snprintf(fname, PATH_MAX, "file_%d.txt", i);
FILE * f = fopen(fname, "w");
if (f != NULL)
{
    // write stuff to f...
    fclose(f);
}

I hope it is clear now, sorry for the inconvenience this might have caused. I appreciate your help.

هل كانت مفيدة؟

المحلول

Your question is not very clear but I'm guessing you mean something like this:

int i = 42;
char fname[PATH_MAX];
snprintf(fname, PATH_MAX, "file_%d.txt", i);
FILE * f = fopen(fname, "w");
if (f != NULL)
{
    // write stuff to f...
    fclose(f);
}

This opens a file named "file_42.txt" for writing.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top