Reading from files using readdir and nextfile
Archives Forums/BlitzMax Bug Reports/Reading from files using readdir and nextfile
| ||
As a Bmax noob I've probably made an error here, but I'm getting strange behavior when using ReadDir/NextFile to read data from a series of text files. Nextfile sucessfully gives the next filename and FILE_STREAM appears to open the file for reading, but Eof(FILE_STREAM) is reached immediately, so no data is read. Only if I add the full path to the filename will it allow me to read the data e.g. FILE_NAME = CDIR + "DATA/" + FILE_NAME (running W7 64) Strict Global CDIR:String; ChangeDir("..") ; CDIR = CurrentDir() If Right(CDIR, 1) <> "/" Then CDIR = CDIR + "/" Local FLAG_CFG Local FOLDER_DATA:int = ReadDir(CDIR + "DATA") Local FILE_NAME:String Local FILE_STREAM:TStream Local DATA_LINE:String Repeat FLAG_CFG = 0 FILE_NAME = NextFile(FOLDER_DATA) If FILE_NAME <> "" Then FLAG_CFG = 1 'FILE_NAME = CDIR + "DATA/" + FILE_NAME - uncomment to have file not eof immediately If Instr(Upper(FILE_NAME), ".CFG") Then FILE_STREAM = ReadFile(FILE_NAME) If FILE_STREAM <> Null While Not Eof(FILE_STREAM) Print ReadLine(FILE_STREAM) Wend CloseStream FILE_STREAM End If EndIf Until FLAG_CFG = 0 CloseDir FOLDER_DATA Last edited 2011 Last edited 2011 |
| ||
I think you have done a mistake:ReadDir(CDIR + "DATA") ->You go through "currentdir/DATA/*". FILE_NAME = NextFile(FOLDER_DATA) FILE_STREAM = ReadFile(FILE_NAME) ->You read from "currentdir/*" because "NextFile" returns a filename but not a full path. One question before you fix your code: Is "FILE_STREAM <> Null" 'true'? If it is something else went wrong. PS: You can use "ExtractExt" to check the filename extension easier. |
| ||
mpmxyz That's what threw me - FILE_STREAM does not return a null after ReadFile(FILE_NAME) and so I assumed it had sucessfully opened the file. (thanks for the ext check tip) Last edited 2011 |
| ||
When I tested your code, ReadFile only returned Null.Strict Global CDIR:String; ChangeDir("..") ; CDIR = CurrentDir() If Right(CDIR, 1) <> "/" Then CDIR = CDIR + "/" Local FLAG_CFG Local FOLDER_DATA:Int = ReadDir(CDIR + "DATA") DebugLog CDIR + "DATA" Local FILE_NAME:String Local FILE_STREAM:TStream Local DATA_LINE:String Repeat FLAG_CFG = 0 FILE_NAME = NextFile(FOLDER_DATA) If FILE_NAME <> "" Then FLAG_CFG = 1 'FILE_NAME = CDIR + "DATA/" + FILE_NAME - uncomment to have file not eof immediately If Instr(Upper(FILE_NAME), ".CFG") Then FILE_STREAM = ReadFile(FILE_NAME) DebugLog "found "+FILE_NAME If FILE_STREAM <> Null DebugLog "read "+FILE_NAME While Not Eof(FILE_STREAM) Print ReadLine(FILE_STREAM) Wend CloseStream FILE_STREAM End If EndIf Until FLAG_CFG = 0 CloseDir FOLDER_DATA What is written via DebugLog? PS: There are a lot useful functions in brl.FileSystem. (e.g. StripSlash) |