Google
Home | File Input 1 [ 1, 2, 3, 4, 5 ]

File Input 1

Reading an Entire File

Read an entire file into memory, print the contents, and terminate the file.

This is the fourth part of the File Input Tutorial contributed by harleyg of PSP-Programming.com's forums (originally posted as generic C code here). Parts one, two, and three need to have been completed before proceeding.

Next we are going to print the buffer/file contents to the terminal.

printf("%s\n", buffer);

This will print the buffer to the screen. If you don't understand how, check out the other C tutorials.

Next, we free the memory we allocated.

free(buffer);

free, is a function used to un-allocate memory you allocated. It requires one parameter, the variable you want to release.

We now end the thread return 0. This shows that everything ran fine if it got to this point. And signals the end of our main function.

     sceKernelSleepThread();
     return 0;
}

And finally we closed the main function with an end bracket.

Your final code should look like this:

#include <pspkernel.h>
#include <pspdebug.h>
#include <stdio.h>
#include <stdlib.h>

#define printf pspDebugScreenPrintf

/* Your callbacks should go here. */

int main (void) {
     pspDebugScreenInit();
     SetupCallbacks();

     FILE * pFile;
     long lSize;
     char * buffer;

     pFile = fopen ( "myfile.txt" , "rb" );

     if (pFile==NULL) sceKernelExitGame();

     fseek (pFile , 0 , SEEK_END);
     lSize = ftell (pFile);
     rewind (pFile);

     buffer = (char*) malloc (lSize);

     if (buffer == NULL) sceKernelExitGame();

     fread (buffer,1,lSize,pFile);

     fclose (pFile);

     printf("%s\n", buffer);

     free (buffer);

     sceKernelSleepThread();
     return 0;
}

There's just one more step, the Makefile. Proceed to part five to finish up the program.

Home | File Input 1 [ 1, 2, 3, 4, 5 ]