Reading UROM Files
From NutWiki
Contents |
Description
This example demonstrates how to read a file from the Micro-ROM (uROM) file system.
For the example to work, you'll need a sub-directory called data, containing the example.txt example.txt should contain some text to be displayed, for example "Hello world!" or "Geez, it works!".
Source Code
#include <dev/board.h> #include <dev/urom.h> #include <fs/uromfs.h> #include <stdio.h> #include <io.h> /* Include our uROM file */ #include "urom_data.c" static char buff[256]; int main(void) { 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(&devUrom, 0, 0)) { printf("UROM error\n"); } fp = fopen("UROM:example.txt", "r"); while (!feof(fp)) { fgets(buff, sizeof(buff), fp); puts(buff); } fclose(fp); for (;;); }
You'll also need a slightly altered Makefile that creates your urom_data.c for you.
PROJ = urom_ex DATADIR = data DATAFILE = urom_data.c include ../Makedefs SRCS = $(PROJ).c OBJS = $(SRCS:.c=.o) LIBS = $(LIBDIR)/nutinit.o -lnutpro -lnutos -lnutnet -lnutfs -lnutcrt -lnutdev -lnutarch TARG = $(PROJ).hex all: $(DATAFILE) $(OBJS) $(TARG) $(ITARG) $(DTARG) $(DATAFILE): $(DATADIR)/example.txt $(CRUROM) -r -o$(DATAFILE) $(DATADIR) include ../Makerules clean: -rm -f $(OBJS) -rm -f $(TARG) $(ITARG) $(DTARG) -rm -f $(DATAFILE)
Details
char buff[256];
defines an array of the type char of 256 bytes. A 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");
First, we set up our stdout device so we can print things to the terminal and output a line with "File read test!"
if (NutRegisterDevice(&devUrom, 0, 0)) { printf("UROM error\n"); }
Here, we register the device driver for the uROM. Notice the difference in naming and capitalization between "DEV_DEBUG" and "devUrom".
fp = fopen("UROM:example.txt", "r");
We can open files from the uROM like any other files. Just prefix the filename with UROM: to tell Nut/OS that we're opening a file from uROM.
while (!feof(fp)) { fgets(buff, sizeof(buff), fp); puts(buff); }
While we haven't reached the end of the file, we read a string into our buffer and print it to the terminal. "fgets" reads a string from a file (strings end at the end of a line so we read the file one line at a time.) The "sizeof(buff)" restricts the amount of characters read to the length of our buffer. We don't want to read more than we can store. "puts" then outputs the buffer to the terminal.
fclose(fp);
Don't forget to close the file after you're done with it.
Output
File read test
Hello world!
See also
| Languages: |
English |
