Tips and Tricks
A place for useful snippets of code...
Find the length of a file
// How to get the length of a file, sford #include "mbed.h" LocalFileSystem usb("usb"); int main() { // open a file FILE* fp = fopen("/usb/file.txt", "r"); if(fp == NULL) { error("Failed to open file.txt!"); } // seek to end of file, and get position (== length in bytes) fseek(fp, 0, SEEK_END); int length = ftell(fp); fseek(fp, 0, SEEK_SET); // return pointer back to start if required printf("File length = %d\n", length); fclose(fp); }
A simple hex viewer
/* Function: hexview * Prints an array of char to stdout in hex. * The data is grouped in two 8 byte groups per line. * Each byte is displayed as 2 hex digits and every * line starts with the address of the first byte. * * There is no text view of a line. * * Variables: * buffer - The array to display. * size - The length of buffer. * * Author: rmeyer */ inline void hexview(char *buffer, unsigned int size) { printf("\n"); for(int i = 0; i < size; ++i) { if((i%16)!=0) { printf(" "); } else { printf("%04X: ", (i)); } printf("%02hhx", buffer[i]); if((i%16) == 7) { printf(" "); } if((i%16) == 15) { printf("\n"); } } printf("\n\n\n"); }
