I want to remove the last new line from the following function:
void WriteToFile(node *tree)
{
void Write(node*);
fp = fopen("dictionary.txt","w");
if(fp==NULL)
{
printf("Cannot open file for writing data...");
}
else //if(tree==NULL)
{
if(tree!=NULL)
{
Write(tree);
}
fclose(fp);
}
}
void Write(node *tree)
{
if(tree!=NULL)
{
fprintf(fp,"%s:%s\n",tree->word,tree->meaning);
Write(tree->left);
Write(tree->right);
}
}
I am using this function to write to a text file the contents of a BST, and I dont want it to write the last new line, how can I remove it?
In a recursive routine like yours, you cannot easily know which is the last call, but you can know what is the first call.
Rather than writing data and, optionally, a newline, consider writing an optional newline followed by data:
But consider the most used definition of a line for text mode files is: a sequence of 0 or more characters folllowed by and including a newline. According to this definitilon all lines have a newline; and the last piece of data in your file is not a line.
At least one badly written program I’ve used fails to process the whole input because of that. My guess is that it does something like
This badly written program would work if the last piece of data included a newline.