3

I have some problems to read correctly 2 files :

filetest1.txt contains :

chocolate
coconut
banana

filetest2.txt contains :

strawberry
orange

procedure :

proc callme {file1 file2} {
   set file1 [open $file1 r]
   set file2 [open $file2 r]
   while {[gets $file1 line1] != -1} {
      while {[gets $file2 line2] != -1} {
         puts "inside : $line1"
      }
      puts "outside : $line1"
   }
   close $file1
   close $file2
}
callme filetest1.txt filetest2.txt

the ouput shows :

inside : chocolate
inside : chocolate
outside : chocolate
outside : coconut
outside : banana

So my question is why there is only :

inside : chocolate
inside : chocolate

I've expected to have :

inside : chocolate
inside : chocolate
outside : chocolate
inside : coconut
inside : coconut
outside : coconut
inside : banana
inside : banana
outside : banana

Thanks.

user2669068
  • 165
  • 1
  • 2
  • 11

2 Answers2

3

You should to change your code to read:

proc callme {file1 file2} {
   set file1 [open $file1 r]
   set file2 [open $file2 r]
   while {[gets $file1 line1] != -1} {
      seek $file2 0 start
      while {[gets $file2 line2] != -1} {
         puts "inside : $line1"
      }
      puts "outside : $line"
   }
   close $file1
   close $file2
}
callme filetest1.txt filetest2.txt

Notice the seek $file2 0 start which gets you back to the beginning of the second file on every iteration of the loop. Hope this helps!

urish
  • 8,943
  • 8
  • 54
  • 75
2

You have nested loops. Inside the first loop you read one line, and then you read every line in the second file. When you go to the second line in the first file, you've already read the second file so the inner while loop never executes.

The simple fix for this is to add the following immediately before the second while:

seek $file2 0 start

That will move the file pointer back to the start of the second file so that you can read it all again.

If these files are smallish (somewhat less than a gig), you can read them all into memory once, split them into a list of lines, and iterate over the lists. That will be much faster. Though, if your files a very small the difference will not be noticeable.

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685