Home > OS >  Need to place strings in different txt files depending on their first letter (A to Z)
Need to place strings in different txt files depending on their first letter (A to Z)

Time:12-12

So, I've been doing this school project for a while now and one of its many parts consists on asking the user for a word input, taking their input and placing it in the file that corresponds to its first letter. CREATING VOIDS IS NOT ALLOWED

Ex. Input: "Orange" --> O.txt Input: "Gerald" --> G.txt

I don't understand how I'm supposed to compare the filename with the first letter of the word. Please, Gods of C, help me out.

CodePudding user response:

It's not as difficult as you may think. First of all, you don't necessarily have to compare anything at all.

Lets say you have the following function: void writeInput(const char* input). What you'll basically want to do, is take the first letter of the input, place it in another string, add the .txt extention and use that as a file path. The most simple way would be to initialize the string with such a path to begin with, and then replace the first letter of it the the input's first letter.

Here is a simple example:

void writeInput(const char* input)
{
   char path[] = " .txt"; //space will be replaces with first letter
   path[0] = input[0]; //assuming input is not empty

   FILE* file = fopen(path, "w");
   if (!file)
   {
      printf("Error openning file");
      exit(1);
   }
   fputs(input, file); //writes input to file
   fclose(file);
}

Please note that using exit(1) is probably not good practice, but this is just an example.

If you didn't know that you'll always use just one letter before the .txt extention, I would recommend using strcat, which is used to concatinate strings together.

CodePudding user response:

The short answer is:

#include<stdio.h>
void string_to_file(const char * str) {
    char buffer[100] = {};             // create a template file

    fprintf("%c.txt", str[0]);         // put the first letter of the
                                       // string in the first letter of
                                       // the file name
    
    FILE * f = fopen(buffer, "a");     // open the file, the "a" mean
                                       // append

    fprintf(f, "%s\n", str);           // print in the file your string
                                       // and a new line

    fclose(f);                         // close file
}
  •  Tags:  
  • c
  • Related