• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 269
  • Last Modified:

reading files

Hi!

Here is my problem:

I got a text file which contains other text file's name (one by line)
Ex:
file1.cfg
file2.cfg
file3.cfg


When I loop through the file with fget to read each filename, and then pass this filename to fopen, it give me a seg fault because of the newline char fget reads. So I first though to use fscanf instead of fget and worked well until I realize it wouldn't read filename containing space and also, it doesn't read 'til the eof like fget did.

So my question is how can I remove the new line char read by fget?

I thought I could use strncpy(dest, source, strlen(source) - 1) but it didn't work :(

Thanks!
HiGiJJ!
0
higijj
Asked:
higijj
  • 3
1 Solution
 
akshayxxCommented:
lets say  u have got the filename in ur variable
char fname[MAXLEN];
and u r sure there is one newline in this . that is at the end .. then do this

quick way
fname[strlen(fname)-1]='\0';
 // this will not work if u have more than one newline in the string fname

here is another dirty but sure way
char *idx;
idx=strchr(fname,'\n');
*idx='\0';




btw show ur program and i'll suggest the exact change required to make it work..
0
 
akshayxxCommented:
>>So my question is how can I remove the new line char read by fget?
this ensures u'll have single new line for each fgets
only if  that has buffer size large enoough , so that it reads the full line..

so once u ensure that, then
fname[strlen(fname)-1]='\0';
is enough .. and before opening file make a check that the fname has something in it
if(strlen(fname)>0){
open the file and check if u were success ful to open the file
}

0
 
higijjAuthor Commented:
Thanks a lot!!

the files are too complicated (not to understand, but spread over many files) to paste it here. but I gave it a try and worked perfectly!

thanks!
0
 
akshayxxCommented:
nice to know it worked .. good luck with rest of ur work
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now