How create a token symbol list string?

I am trying to construct a symbol list of the entire SP500 from file to result into a string format like this:
mySymList = "AAPL,C,CAT,GE,IBM,INTC,MSFT";

But when I do this, it seems to be adding a line return character for every line. How do I construct this comma delimited symbol list (token list)?

fh = fopen( "C:\\temp\\SP500.txt", "r"); 
if( fh ) 
{ 
	count = 0;
   mySymList = "";
   while( ! feof( fh ) ) 
   { 
		count ++;
		line = fgets( fh ); 
		mySymList = mySymList + line + ",";
   }  
} 
else 
{ 
   printf("ERROR: file can not be found (does not exist)"); 
} 
fclose(fh);

@vjsworld try this:

mySymList = "";
fh = fopen( "C:\\temp\\SP500.txt", "r"); 
if( fh ) 
{ 
   count = 0;
   mySymList = "";
   while( ! feof( fh ) ) 
   { 
		count ++;  // not used....
		line = fgets( fh ); 
        // Remove new line chars
		line = StrReplace(line, "\n", "");
		mySymList = mySymList + line + ",";
   }  
} 
else 
{ 
   printf("ERROR: file can not be found (does not exist)"); 
} 
fclose(fh);
_TRACE(mySymList);

StrReplace should be placed outside of loop. And fclose within fh statement.

count = 0;
mySymList = "";

fh = fopen( "C:\\temp\\SP500.txt", "r"); 

if( fh )
{
    while( ! feof( fh ) )
    {
        count ++;
        line = fgets( fh );
        mySymList += line + ",";
    }
    
    fclose(fh);
}
else
{
    printf( "ERROR: file can not be found (does not exist)" );
}

mySymList = StrTrim(StrReplace(mySymList, "\n", ""), ",");
5 Likes

Excellent. Thanks guys!

@vjsworld be sure to use the @fxshrat solution since his code is faster calling the StrReplace ONCE outside of the loop (instead of what I was doing - in this case calling 500 it times.... :scream: - to remove the newline character).
As he pointed out, take note also of the correct placement of the fclose() call.

Moreover, at the end of code, he added a StrTrim() call to remove the unneeded last comma,

As usual, he shows us how to write perfect code! Thanks.

Yes, that was the code that I went with already. I noticed those improvements.

Thanks again!