Search code examples
carraysfopen

how do I open files using an array in c


I want to open file named ex1, ex2, ex3 ...exn etc. Now when i put the value of n like, n=1, ex1 will be opened for, n=2, ex2 file will be opened and then I will read or write my c program output array from or into it. can the name of the file be given as a string?

As I am new with programing please help me to solve this problem.


Solution

  • Normally when you open a file you use the function fopen

    fp = fopen ("file.txt", "w+");
    if (fp == NULL)
    {
        exit(1); // Or you can raise some error code and return if this code is in a function.       
    }
    // Process the file
    

    Now in your case, you need to manipulate the filename. So you can take a C string for this.

    char filename[10];
    
    // N is set from code above
    
    sprintf(filename,"ex%d",N);
    fp = fopen (filename, "w+");
    
    // Further behaviour is same