Reading PHAT Files

From NutWiki

Jump to: navigation, search

Contents

Test Environments

Hardware
Comments
Nut/OS
4.6.4
Nut/OS
4.7.4
Nut/OS
4.8.0
Ethernut 3.0 E Compiler Error OK
Binaries
NO
EIR 1.0 C Set jumper JP1
to DEBUG mode.
Compiler Error OK
Binaries
OK
Binaries
AT91SAM7X-EK NT NT
AT91SAM9260-EK NT NT
Compiler: ARM-GCC 4.2.2 ; AVR-GCC 4.3.0

Description

This example demonstrates how to reada file with the PHAT file system from a MMC (SD) card.

Note, that this example is consecutive to Writing PHAT Files. We will read a file, previously written by that example.

Source Code

#include <dev/board.h>
#include <dev/nplmmc.h>
#include <fs/phatfs.h>
#include <stdio.h>
#include <io.h>
#include <fcntl.h>
#include <errno.h>
 
char buff[256];
 
int main (void)
{
    int hvol;
    FILE *fp;
 
    unsigned long baud = 115200;
 
    NutRegisterDevice(&DEV_DEBUG, 0, 0);
 
    freopen(DEV_DEBUG_NAME, "w", stdout);
    _ioctl(_fileno(stdout), UART_SETSPEED, &baud);
 
    puts("File read test\n");
 
    if (NutRegisterDevice(&devPhat0, 0, 0)){
    	printf("PHAT file system error\n");
    }
 
    if (NutRegisterDevice(&DEV_MMCARD, 0, 0)){
    	printf("MMC block device error\n");
    }
 
    hvol = _open("MMC0:1/PHAT0", _O_RDWR | _O_BINARY);
 
    if (hvol == -1) {
        printf("Mount error %d\n", errno);
    }
 
    fp = fopen("PHAT0:/TEST.TXT", "r");
    fscanf(fp, "%s", &buff[0]);
    puts(buff);
 
    fclose(fp);
    _close(hvol);
 
    for(;;);
}

Details

char buff[256];

defines an array of the type char of 256 bytes. An char array is also called string.

unsigned long baud = 115200;
 
NutRegisterDevice(&DEV_DEBUG, 0, 0);
 
freopen(DEV_DEBUG_NAME, "w", stdout);
_ioctl(_fileno(stdout), UART_SETSPEED, &baud);
 
puts("File read test\n");

After setting our stout and printing out a banner,

if (NutRegisterDevice(&devPhat0, 0, 0)){
    printf("PHAT file system error\n");
}

registers the PHAT file system and prints out an error message, if an error occured.

if (NutRegisterDevice(&DEV_MMCARD, 0, 0)){
    	printf("MMC block device error\n");
    }

registers the MMC block device and prints out an error message, if an error occured.

hvol = _open("MMC0:1/PHAT0", _O_RDWR | _O_BINARY);

mounts a PHAT partition called "PHAT 0".

if (hvol == -1) {
    	printf("Mount error %d\n", errno);
    }

prints out an error message, if an error occured mounting the partition.

fp = fopen("PHAT0:/test.txt", "r");

opens a file "test.txt" and prepares it to be read. Now the pointer fp points to that text file.

fscanf(fp, "%s", &buff[0]);

reads the string (&s) in the file, fp points to, and puts it into the "buff" array.

puts(buff);

puts out the content of buff, namely the string read from the text file.

fclose(fp);
_close(hvol);

Finally, we close the file and unmount the partition.

Output

File read test
HelloFile


See also

Personal tools