Codemii Tutorial 10
Codemii Tutorial 10
Codemii Tutorial 10
http://www.codemii.com/2009/03/02/tutorial-10-using-the-filesystem/
Its een a while since I put up a tutorial and I hope that y now you ha!e a asic understanding of programming for the "ii. #o that Im a le to $eep producing these tutorials Ill try to focus on small pieces of code instead of the whole application and how the code can e applied. %he e&planation of #imon was a it too long '(. %his tutorial is also a it longer than I e&pected. In this tutorial well co!er initialising the filesystem) creating/deleting directories/files and reading/ writing files. %han$s to *oed* for his +,% init code from +%-ii !0.0... /ote: %his tutorial is for 0e!1it--2 r1.. 3sers of r14 will ha!e to prepend #0:/ whene!er accessing the filesystem.
%he a o!e *ust reads) if we cant initialise the +,% filesystem) then print an error message and e&it. %he ne&t thing to chec$ 5which isnt mandatory( is to see if we can open the filesystem which is done with the code elow.
if (!$an%open%root%fs()) { printf("Unable to open root filesystem, exiting. n")! exit(")! # bool $an%open%root%fs() { DI&%IT'& (root ) *iropen("+")! if (root) { *ir$lose(root)! return true! # return false! #
1/4
"e use diropen to chec$ if we are a le to open the root directory and if so it returns true. 6$) so we can open the filesystem. "e can add another chec$ to ma$e sure that we can actually change the current wor$ing directory to the root 5/(:
if ($,*ir("+")) { printf("-oul* not $,ange to root *ire$tory, exiting. n")! exit(")! #
,nd now were done with the initialisation. "e can place this all in a function to ma$e things a it cleaner. "e call our own die5( function if something has failed. Its always good practise to unmount the filesystem when e&iting your application. %his can e done y calling fat3nmount50('.
.oi* initialise%fat() { if (!fatInitDefault()) *ie("Unable to initialise FAT subsystem, exiting. n")! if (!$an%open%root%fs()) *ie("Unable to open root filesystem, exiting. n")! if ($,*ir("+")) *ie("-oul* not $,ange to root *ire$tory, exiting. n")! # bool $an%open%root%fs() { DI&%IT'& (root ) *iropen("+")! if (root) { *ir$lose(root)! return true! # return false! # .oi* *ie($,ar (msg) { perror(msg)! sleep(/)! fatUnmount(")! exit(")! #
,s you can see a o!e the die function accepts a string of characters 5denoted y char 7( and then prints out the string using perror5(. %he thing a out perror is it will print out the string supplied as well as any error that has occurred. +or e&le if you are trying to open a file and it doesnt e&ist) perror might print something li$e 8/o such file or directory9 which is always helpful. ,fter that we *ust pause for . seconds) unmount the filesystem and e&it the application.
2/4
Creating Directories
"e can create a directory y using m$dir. m$dir ta$es two arguments) the directory to create and the permissions to set on the directory. "e can ignore the permissions and *ust set them as 0::: 5e!eryone has access to read) write and delete(.
m0*ir("+test", "111)!
%he a o!e would create a directory called /test on the root of the de!ice we are accessing. m$dir returns 0 if the directory was created successfully otherwise it returns -1. "e can chec$ for errors y doing the following:
if (m0*ir("+test", "111) )) 23) { *ie("-oul* not $reate +test *ire$tory. n")! #
%his will run the m$dir command and if it returns -1 it will print the string specified and perror5( will print out the error message.
Removing Directories/Files
"e can remo!e a directory or a file y using unlin$5path('
unlin0("+test+myfile.txt")! unlin0("+test")!
%he a o!e would remo!e the file called myfile.t&t and then the directory /test. "e can also chec$ for errors e&actly the same as m$dir:
if (unlin0("+test") )) 23) { *ie("-oul* not *elete *ire$tory+file. n")! #
Reading Files
%here are !arious ways to read files. "ell stic$ to the easiest way which is reading the file one line at time so that we may process each line. %his might e useful say if youre de!eloping a game that has multiple le!els and each line might represent an o *ects & and y co-ordinates. +irst we need to open the file in read mode as elow.
FI4' (f ) fopen ("myfile.txt", "rb")!
3/4
"e need store each line to a !aria le so that we are a le to process the line. %his !aria le is file;line and is an array of characters which holds 20 characters 5Im assuming that our & and y co-ordinates are etween 1 to 3 characters in length) so 20 is more than enough(. If say you had a long line of te&t) you would ha!e to change 20 to say .00 or more depending on how long each line was. ,fter that we *ust ha!e the line;num er which *ust counts the num er of lines. /ow we reach the while loop) here we use the fgets function. fgets allows us to specify the amount of characters to read in the line or until the line ends. %he first argument is a pointer to our array of characters which is where the information from the file will temporarily e stored. %he second argument is the num er of characters to read) again we use 20. %he third argument is the pointer to the file) which is f in this case. In e!ery loop) file;line will e updated with the ne&t line from the myfile.t&t file. %his continues until we reach the end of the file. "e then print out the line num er and the contents of the line at each loop. ,fter we ha!e reached the end of the file) we can close the file y using fclose5f(' #o lets say that our file contains the following data which represents & and y co-ordinates: 32 .< 3= =< 23= 99 3<. 23= =.3 3=: "e need a place to store the & and y co-ordinates) a simple e&le is:
int x%pos9; ) { ", ", ", ", "#! int y%pos9; ) { ", ", ", ", "#!
"e would need to modify our while loop to rea$ up each line) as we need the & and y co-ordinates in different !aria les. >ere we can use the string to$eni?er 5stro$( to rea$ up the line. strto$ ta$es 2 arguments) the string to to$eni?e and a list of delimiters' which *ust means the characters to find that will determine a split in the string. +or our e&le the delimiters would *ust e a space 59 8( which would rea$ the line into 2 parts. %he delimiter isnt included in any of the parts.
=/4
/ow if we where to store each part directory into the integer !aria le the compiler would complain 5char eing stored in an int() so we need to change the string of characters to an int. %his can e done using atoi5string( which *ust con!erts the string into an integer.
6,ile (fgets (file%line, :", f)) { $,ar (temp%string! temp%string ) strto0 (file%line, " ")! if (temp%string !) 7U44) { x%pos9line%number; ) atoi(temp%string)! temp%string ) strto0 (7U44, " ")! if (temp%string !) 7U44) { y%pos9line%number; ) atoi(temp%string)! # # line%number>>! #
"e firstly assign a lan$ pointer. "e run strto$ on our file;line !aria le which contains the line of te&t. temp;string would then e e@ual to the first to$en in the line of te&t) which is 832A. #ince temp;string has a !alue) we assign element 0 of &;pos with the integer !alue of 32. "e run strto$ again) this time with the first argument of /3BB. Cou use the /3BB argument in strto$ if you wish to continue rea$ing up a string. %he ne&t to$en is 8.<A which we assign the integer !alue of .< to element 0 of y;pos. "e then increase the line;num er) and so on.
Writing files
,s with reading files) writing files can e done in different ways. , simple way of writing files would use the fputs function which ta$es 2 arguments) the string to write to the file and the pointer to the file.
FI4' (f ) fopen ("myfile.txt", "6b")! if (f )) 7U44) { *ie("-oul* not open myfile.txt file for 6riting. n")! # else { int x! for (x ) "! x ? line%number! x>>) { $,ar temp%string9:";! sprintf(temp%string, "<i <i", x%pos9x;, y%pos9x;)! fputs (temp%string ,f)! # f$lose(f)! #
./4
/ote that 8r 9 has changed to 8w 9 5the w means write(. "ell use the same e&le as in the reading e&le) e&cept in this case we wish to write our & and y co-ordinates to the file. "ell assume that you ha!e the line;num er !aria le and that it e@uals .. "e do a for loop until we reach line;num er 5.(. #o we need to do the opposite of strto$) so that we are a le to add the two num ers and a space in etween. "e also need to change the integer !alues of & and y into strings. "e can do this using sprintf which has 3 arguments and is *ust li$e printf e&cept it prints the output to a string. %he arguments are the string to output to) the te&t to print and the !aria les to print. "e ha!e the temp;string !aria le which is empty) we do a sprintf which con!erts 8Di Di9 to 832 .<A. ,fter we con!ert the integers to a string) we write this temp;string to our file and repeat until we are done. /ote: I ha!e e&perienced issues when using sprintf multiple times in a row which can cause issues with the !aria les sprintf is writing to. ,nd thats it' were done for this tutorial. Cou should now $now how to preform different functions on files/folders which should ma$e your life easier if you are say ma$ing a multi-le!el game or wish to sa!e some simple settings to a file. Eemem er that there is a lot more error chec$ing that could e done ut for the purposes of this tutorial its *ust too much to do. #ee you ne&t timeF
4/4