Hello

Im new to C programming, im trying to learn how to create a textfile with whatever name the user of the program wants.

something like this, please ignore that this code wont work, its just so you might understand how i am thinking:

FILE *file;
  printf("name of the file: ");
  scanf("%s",adress);
  file=fopen("%s",adress,"a+");
  
  if(file==NULL){
    printf("File does not exist, creating file with desired filename");

So, im thiking to name the file to whatever the user inputs in a string, is this possible or should i consider some other way than string?

Thanks

Dani AI

Generated

Short answer: was right that you should pass a filename string variable to the file-open function. Below is a safer, practical pattern and a few caveats that extend the brief exchange here.

Use a bounded input read (not the plain %s) so filenames with spaces are accepted and buffer overruns are avoided. Trim any trailing newline or carriage return, verify the result is nonempty, then open the name with the file mode that matches the intent (create/truncate vs append). Always check the returned file pointer for failure and report the error (for example with perror or strerror(errno)).

Example pattern:

char filename[260];
if (!fgets(filename, sizeof filename, stdin)) { /* handle input error */ }
/* strip trailing newline/cr */
size_t n = strlen(filename);
while (n > 0 && (filename[n-1] == '\n' || filename[n-1] == '\r')) filename[--n] = '\0';
if (n == 0) { /* handle empty filename */ }
FILE *fp = fopen(filename, "w"); /* choose mode based on desired behavior */
if (!fp) { perror("fopen"); /* handle open error */ }
/* use fp, then fclose(fp) */

Important notes and gotchas:

  • Validate filenames for your platform (Windows disallows some characters and reserved names). Paths, permissions, and current working directory affect where the file is created.
  • Choose the right mode: some modes create files, others require the file to exist.
  • For Microsoft CRT consider fopen_s if you prefer that API.
  • On production code consider limiting and canonicalizing paths to avoid directory traversal or accidental overwrites.

References: fgets documentation and fopen documentation.

Recommended Answers

All 2 Replies

just remove the "%s" -- its not necessary because adress is already a string that contains the filename

file=fopen(adress,"a+");

Ah i see!

Thank you very much!

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.