C:Is there a way to use scanf input to fopen?

C:Is there a way to use scanf input to fopen?

Page 1 of 1

2 Replies - 5181 Views - Last Post: 01 August 2008 - 09:57 AM Rate Topic: -----

#1 breekbot  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 21
  • Joined: 01-August 08

C:Is there a way to use scanf input to fopen?

Posted 01 August 2008 - 08:52 AM


This is one of my attemps but it doesnt work! im out of ideas google wasnt verry helpfull.
Thanx in advance!

breekbot



#include <stdio.h>
main() {
  
char filename[20];

printf("Enter filename:\n");

scanf("%c",&filename);

  FILE *file;

  file = fopen("path to filename %c", "w+", filename); /* <-----------this doesnt work*/
  
  if(file==NULL) {
	printf("Error: can't create file.\n");
	
	return 1;
  }
  else {
	printf("File created. Now closing it...\n");
	fclose(file);
	return 0;
  }
}


This post has been edited by breekbot: 01 August 2008 - 08:55 AM


Is This A Good Question/Topic? 0
  • +

Replies To: C:Is there a way to use scanf input to fopen?

#2 NickDMax  Icon User is offline

  • Can grep dead trees!
  • member icon

Reputation: 2250
  • View blog
  • Posts: 9,245
  • Joined: 18-February 07

Re: C:Is there a way to use scanf input to fopen?

Posted 01 August 2008 - 09:11 AM

Yea, fopen does not stand for "formatted open" but "file open" so you can't really expect it to work like printf or scanf...

file = fopen(filename, "w+"); may work better.

but apparently you want to be able to add a path to the file name, in this case you may want to look into using strcat() or if you are a big fan of the printf() style formatting then you can try sprintf() which allows you to format a string using a "printf" style function.

by the way, when reading in your file name, you may wish to use "%19c" to ensure the user does not cause a buffer overrun error by typing more than 19 characters.
Was This Post Helpful? 0
  • +
  • -

#3 breekbot  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 21
  • Joined: 01-August 08

Re: C:Is there a way to use scanf input to fopen?

Posted 01 August 2008 - 09:57 AM

View PostNickDMax, on 1 Aug, 2008 - 09:11 AM, said:

Yea, fopen does not stand for "formatted open" but "file open" so you can't really expect it to work like printf or scanf...

file = fopen(filename, "w+"); may work better.

but apparently you want to be able to add a path to the file name, in this case you may want to look into using strcat() or if you are a big fan of the printf() style formatting then you can try sprintf() which allows you to format a string using a "printf" style function.

by the way, when reading in your file name, you may wish to use "%19c" to ensure the user does not cause a buffer overrun error by typing more than 19 characters.



Both of your suggestions are really help full thank you very much !!!

breekbot

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1