I have the below GML code where I am attempting to read strings from "mygame.txt". When I run the code, the array is just filled with "". I found the buffer section of code and I can see that the var s actually contains the contents of my game. Any idea why the array, arr[] does not properly read the string?
lines= 0
var file = file_text_open_read("mygame.txt"); // need to store in "data files" folder
if (file!= -1){
while (!file_text_eof(file)) {
file_text_readln(file);
lines++;
}
var file_buffer = buffer_load("mygame.txt");
var s = buffer_read(file_buffer, buffer_string);
buffer_delete(file_buffer);
for (var i = 0; i < lines; ++i;){
arr[i] = file_text_read_string(file);
file_text_readln(file);
}
file_text_close(file);
for (var i = 0; i < 1; ++i;){
}}
The array arr[] is displaying blanks because in
while (!file_text_eof(file)) {
file_text_readln(file);
lines++;
}
I was reading the file through to the end of the file in order to mistakenly get the # of lines in the file for the for loop.
for (var i = 0; i < lines; ++i;){
arr[i] = file_text_read_string(file);
file_text_readln(file);
}
At this point, I am already at the end of the file and therefore no more lines exist. The above for loop processed regardless because the it doesn't care that I was already at the end of file. So all of the indexes in arr[] are blank because it's trying to read lines that don't exist.
To resolve, after the while loop I closed and reopened the file before the for loop.
lines= 0 var file = file_text_open_read("mygame.txt"); // need to store in "data files" folder
if (file!= -1){
while (!file_text_eof(file)) {
file_text_readln(file);
lines++;
}
file_text_close(file);
file_text_open_read(file);
for (var i = 0; i < lines; ++i;){
arr[i] = file_text_read_string(file);
file_text_readln(file);
}
file_text_close(file);
for (var i = 0; i < 1; ++i;){
}}
Another code example by YellowAfterlife is the proper coding
lines = 0;
var file = file_text_open_read("mygame.txt");
if (file != -1) {
while (!file_text_eof(file)) {
arr[lines] = file_text_read_string(file);
file_text_readln(file);
lines++;
}
file_text_close(file);
// arr is now populated with lines from the file
}