Page 1 of 1

Write text file question

PostPosted: Fri May 27, 2011 6:35 am
by Leif
Encountered a problem

I have several "text_string"actors , and one "text_string_new " actor containing text. Task is to write text from those actors into text file. Program (see code) writes them into one string. And i want to make it list.

I mean:
text_string_newtext_string 0text_string 1text_string 2text_string 3text_string 4 - it's current result

But i need
text_string_new
text_string 0
text_string 1
text_string 2
text_string 3
text_string 4


What i'm doing wrong ?

Code: Select all
int i;
Actor*A1;

FILE * textFile = fopen("textFile.txt", "w");  // open file

fputs(text_string_new.text,textFile); // write new string first

for (i=0; i<ActorCount("text_string"); i++)
{
A1=getclone(getFullName("text_string",i));
fputs(A1->text,textFile);             // write other strings
}

fclose(textFile);


P.S:
getFullName function gets name of actor in "name.cloneindex" format

Re: Write text file question

PostPosted: Fri May 27, 2011 7:18 am
by skydereign
Strings don't end in newlines '\n', they end in null '\0'. So the strings you are writing into the file don't have a newline character, therefore there aren't any newlines printed in the text file. If you want to insert a newline, you can just use fputc.
Code: Select all
fputc('\n', textFile);


Or, instead of fputs, you can use fprintf, and add the newline there.
Code: Select all
fprintf(textFile, "%s\n", text_string_new.text);

Re: Write text file question

PostPosted: Fri May 27, 2011 9:27 am
by Leif
Thanks ! It works ))

Re: Write text file question

PostPosted: Fri May 27, 2011 10:43 am
by Leif
Hmm... and the second question...
How to delete second empty line from text string ? :?:

Re: Write text file question

PostPosted: Fri May 27, 2011 8:50 pm
by skydereign
Do you want a function that removes extra white space from the end of the string? Or, would just checking if the string you are about to add to it is empty or not? If the latter, just use strcmp to see if the line is empty.
Code: Select all
if(strcmp(A1->text, "")!=0)
{
    fprintf(textFile, "%s\n", A1->text);
}


That will work if you don't want to add empty lines, but if you meant the text had a newline in it, then you'd have to do something else. Either use strncpy or physically remove the new lines.