A block of code that won't work. fopen function and% d

I have been trying to open multiple files using counter "j + 1" and "% d" but it won't work. here is a code snippet.

#include <stdio.h>  
#include <alloc.h>

FILE *string;
int j=0;

int main(void)
{   
    for (j=0;j<10;j++)
    {
        string = fopen(("C:\\playlist%d.txt",j+1),"w+t");
        fclose(string);
    }
    return 0; 
}  

      

+3


source to share


3 answers


You need to use an array to create a filename with sprintf

and use an array in the call fopen

.



int main(void)
{   
   char filename[100]; // Make the array large enough
   for (j=0;j<10;j++)
   {
      sprintf(filename,"C:\\playlist%d.txt",j+1);
      string = fopen(filename,"w+t");
      fclose(string);
   }
   return 0; 
}  

      

+2


source


EDIT This question originally had a C ++ tag .


FILE* string;
...
string = fopen(("C:\\playlist%d.txt",j+1),"w+t");

      

It seems you wanted to create a filename string with an integer value embedded inside.



(BTW: choosing "string" as the variable name is FILE*

not very useful, I would suggest using something more meaningful ...)

Since this question is noted [c++]

, you can use a handy string class with its operators overloaded and a helper function for that to convert an integer to e.g. std::to_string()

std::string

std::string fileName = "C:\\playlist";
fileName += std::to_string(j+1);
filename += ".txt";

FILE* file = fopen(filename.c_str(), /* other params */);

      

PS In addition to C FILE*

, C ++ has special file stream classes available for file management, for example std::fstream

and related to them.

+1


source


EDIT: The question was originally tagged C ++

Since this is marked as C ++ you can do it with std::string

andstd::fstream

int main()
{
    std::string filename = "C:\\playlist";
    std::fstream file;
    for (int i = 0; i < 10; i++)
    {
        file.open(filename + to_string(i) + ".txt");
        // do stuff
        file.close();
    }
    cin.get();
    return 0;
}

      

+1


source







All Articles