Envision, Create, Share

Welcome to HBGames, a leading amateur game development forum and Discord server. All are welcome, and amongst our ranks you will find experts in their field from all aspects of video game design and development.

[Resolved] Saving a file AS-IS

Status
Not open for further replies.

Tdata

Sponsor

How would you save a file as-is? Basicly i want to create a text document and dump an array into it and it print out all the values then save. Ex.

Winners.txt
First prize:
$winners[0]
Runners up:
$winners[1]
$winners[2]
$winners[3]
$winners[4]
$winners[5]
 
Just build the string and write it to an open file stream.
Code:
string = "First prize:\n#{$winners[0]}\nRunners up:"
for i in 1..5
  string += "\n" + $winners[i]
end
file = File.new('Winners.txt', 'wb')
file.write(string)
file.close
 
try calling each line at once
Code:
strings = []
strings.push "First prize:"
strings.push $winners[0]
strings.push "Runners Up:"
for i in 1..5
  strings.push $winners[i]
end
file = File.new("Winners.txt", "wb") # <- Important that it has that 'b'
for i in 0...strings.size
  file.write string[i]
end
file.close
 
My mistake, sorry. ^^ This works:
Code:
strings = []
strings.push "First prize:\n"
strings.push $winners[0] + "\n"
strings.push "Runners Up:\n"
for i in 1..5
  strings.push $winners[i] + "\n"
end
file = File.new("Winners.txt", "w+")
for i in 0...strings.size
  file.write strings[i]
end
file.close
 
Did you even try it? Yes it does work. Try it. Put this in main, open Winners.txt
Code:
$winners = ['Fred', 'Johnson', 'Peter', 'Julie', 'Pat', 'Steve']
string = "First prize:\n#{$winners[0]}\nRunners up:"
for i in 1..5
  string += "\n" + $winners[i]
end
file = File.new('Winners.txt', 'wb')
file.write(string)
file.close
 
Well that's strange, for me it works perfect. Is it because I'm on Windows 2000 or something? Does it work with 'w+' instead of 'wb'?

EDIT:
file = File.new('Winners.txt', 'wb')
changes to
file = File.new('Winners.txt', 'w+')
 
used the size function for the array ;)
Code:
$winners = ['Fred', 'Johnson', 'Peter', 'Julie', 'Pat', 'Steve']
string = "First prize:\n" + $winners[0] + "\nRunners up:"
for i in 1...$winners.size
  string += "\n" + $winners[i]
end
file = File.new('Winners.txt', 'w+')
file.write(string)
file.close
 
Status
Not open for further replies.

Thank you for viewing

HBGames is a leading amateur video game development forum and Discord server open to all ability levels. Feel free to have a nosey around!

Discord

Join our growing and active Discord server to discuss all aspects of game making in a relaxed environment. Join Us

Content

  • Our Games
  • Games in Development
  • Emoji by Twemoji.
    Top