Hey how do I make so this would save myfile as a text file?

FILE * pFile;
char filename[256] = "myfile";
pFile = fopen (("%s",filename), "w");
fclose (pFile);

This creates a File named myfile but not as a textfile.
I tried to add .txt after %s but that doesn't help.

Thanks
John

Recommended Answers

All 5 Replies

char filename[256] = "myfile";
   FILE * pFile = fopen (filename, "w");
   if (file)
   {
      /* Do stuff. */
      fclose(file);
   }
   fclose (pFile);

Hey how do I make so this would save myfile as a text file?

pFile = fopen (("%s",filename), "w");

I tried to add .txt after %s but that doesn't help.

Let me guess: you are a Pythonian, right?
In C, ("%s",filename) is a comma expression; it evaluates to whatever is mentioned last, that is to filename . Now, if you need a "myfile.txt" file, why don't you just spell it out explicitly:

char filename[256] = "myfile.txt";

Thanks for the replies :)

@nezachem
Yes I know that would work. But lets say that a user has to type in a save file name. Then if he only typed in "myfile"how could i add the .txt after the answer? Well I could force him to type in the ".txt" after the filename. But I don't want to do that.

Look at sprintf() then.

Use a string handling function, then feed the resulting string to fopen. Don't expect fopen to be any string handling function you'd like it to be.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.