Impression d'un fichier dans C

Comment puis-je imprimer un vide .txt file j'ai déjà créé?

J'ai déjà imprimer les résultats de la console, et maintenant je veux imprimer un fichier nommé "Output.txt". J'ai essayé un couple de choses qui n'ont pas travaillé, mais je pense que c'était plus facile de créer un double de printDictionary() spécifiquement pour l'impression dans un fichier appelé printDictionaryToFile(). Je suis un peu perdu sur la façon de le faire bien. Quelqu'un peut-il me corriger sur l'endroit où je suis allé mal? J'ai déjà ajouté un supplément de FILE type appelé *out pour ma sortie vers un fichier.

#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;
}
Utiliser fopen("filename.txt", "w") et de fprintf().

OriginalL'auteur Silent Phantom | 2013-09-23