Printing to a file in C

48,340

You can use the fprintf() function, which is quite similar to printf() in the way it works.

Here is an example:

FILE *fp;
int myInt = 5;
fp = fopen("Output.txt", "w");// "w" means that we are going to write on this file
fprintf(fp, "This is being written in the file. This is an int variable: %d", myInt);
fclose(fp); //Don't forget to close the file when finished

The output on your file would be this:

This is being written in the file. This is an int variable: 5

Worth to mention that opening the file using w as parameter will destroy the file's content every time you open it.

Share:
48,340

Related videos on Youtube

Silent Phantom
Author by

Silent Phantom

Updated on September 27, 2022

Comments

  • Silent Phantom
    Silent Phantom over 1 year

    How do I print to an empty .txt file I already have created?

    I already print the results to the console, and now I want to print to a file named "Output.txt". I've tried a couple of things that haven't worked, but I think it was easier to create a duplicate printDictionary() specifically for printing to a file called printDictionaryToFile(). I'm a little lost on how to do it though. Can anyone correct me on where I went wrong? I already added an extra FILE type called *out for my output to a file.

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <ctype.h>
    #include <stddef.h>
    
    #define PUNC    " \t\n\r,;.:!()[]{}?'\""
    typedef struct node node;
    
    typedef struct node {
        char *word;
        int count;
        node *left;
        node *right;
    } node;
    
    
    void insert(node ** dictionary, char * word) {
        int result;
        node * entry;
    
        if (word == NULL || dictionary == NULL)
            return;
        if (*dictionary == NULL) {
            entry= (node *) malloc(sizeof(node));
            strcpy( entry->word= (char *) malloc(strlen(word) + 1), word);
            entry->left= entry->right= NULL;
            entry->count= 1;
            *dictionary= entry;
            return;
        }
        result = strcmp(word, (*dictionary)->word);
        if ( result < 0 )
            insert(&(*dictionary)->left, word);
        else if (result > 0)
            insert(&(*dictionary)->right, word);
        else
            ++(*dictionary)->count;
    
        return;
    }
    
    
    void printDictionary(node * dictionary) {
        if (dictionary == NULL)
            return;
        printDictionary(dictionary->left);
        printf( "%s = %d\n", dictionary->word, dictionary->count);
        printDictionary(dictionary->right);
    
        return;
    }
    
    
    void printDictionaryToFile( node * dictionary ) {
        if (dictionary == NULL)
            return;
        printDictionaryToFile(dictionary->left);
        fprintf(out, "%s = %d\n", dictionary->word, dictionary->count);
        printDictionaryToFile(dictionary->right);
        return;
    }
    
    
    void freeDictionary( node ** dictionary ) {
        if (dictionary == NULL || *dictionary == NULL)
            return;
        freeDictionary(&(*dictionary)->left);
        freeDictionary(&(*dictionary)->right);
        free((*dictionary)->word);
        free(*dictionary);
        *dictionary= NULL;
        return;
    }
    
    
    int main( int argc, char *argv[] ) {
        FILE *fp, *out;
        out = fopen("Output.txt", "w");
        char b[1000], *s;
        node *dictionary= NULL;
        int i;
    
        for (i= 1; i < argc; ++i) {
            if ((fp = fopen(argv[i], "r")) == NULL) {
                fprintf(stderr, "File %s can not be opened.\n", argv[i]);
                continue;
            }
            for (s = fgets(b, sizeof(b), fp); s != NULL; s = fgets(b, sizeof(b), fp)) {
                char *word;
                for (word= strtok(b, PUNC); word != NULL; word = strtok(NULL, PUNC))
                    insert(&dictionary, strlwr(word));
            }
            fclose(fp);
        }
        printDictionaryToFile(dictionary);
        printDictionary(dictionary);
        freeDictionary(&dictionary);
        return 0;
    }
    
  • Silent Phantom
    Silent Phantom over 10 years
    Ok so does this work for BST's because I see you have the %d to print a num. Also does that mean I dont have to alter any of the printDictionaryToFile() code everything I need to do is in the main()
  • Natan Streppel
    Natan Streppel over 10 years
    using %d to print an integer was just a way of demonstrating the similarity of fprintf and printf. You can use %s for strings and so on. In your case, you could use, instead of your printf function, fprintf(pointerToFile, "%s = %d\n", dictionary->word, dictionary->count );
  • Silent Phantom
    Silent Phantom over 10 years
    Ok I now it only prints one word I want it to print each like it does in my console what should I do now?
  • Natan Streppel
    Natan Streppel over 10 years
    Actually, if you are using it as said here, fprintf would have to write in your file exactly what your printf function was writing in your console. What is the output that you are getting?
  • Silent Phantom
    Silent Phantom over 10 years
    well in my console I get this huge list of words with how many times each appears in the text. While in the file I get the same thing except its just one word instead of the entire list. Also I using a function to print the words in the console thats why I thought I should have an identical method to that one.
  • Natan Streppel
    Natan Streppel over 10 years
    Are you opening the file every time you write into it? Remember that, about fopen, "using w as parameter will destroy the file's content every time you open it.". You only need to open the file once
  • Silent Phantom
    Silent Phantom over 10 years
    I think imm doing it right ill up date the code on here for you to see.
  • Natan Streppel
    Natan Streppel over 10 years
    you are not passing your out pointer to the function, so the function has no out variable within it's scope. This won't even compile. Try to make this: void printDictionaryToFile( node * dictionary, FILE *out ) getting your out variable and let me know how did it go
  • Silent Phantom
    Silent Phantom over 10 years
    Just one error in the printTofile where i say printToFile(dictionary->left) I need to put something else inside that and putting output doesnt work.
  • Natan Streppel
    Natan Streppel over 10 years
    Pass the variable that you got as a parameter, which would be, following my example, out. If it doesn't work I'll update my answer, since this discussion is getting too long for the comments area.
  • Silent Phantom
    Silent Phantom over 10 years
    Thank you I got it running perfectly.

Related