Fatfs string comparison for fno.fname - c

I have an issue regarding reading the size of a file on my SD card. The sizes of these files will vary in the application, I therefore, need to get the size of the file. If I run the below code I can see the files in my directory along with their size.
What I need to do is store the size of the DATA.CSV file as a variable.
How do I add a comparision to get the fno.fsize when the listing is "data.csv
This prints out:
00> Listing directory: /00> 0 EVENTLOG.CSV <DIR> SYSTEM~1 183600 DATA.CSV ```
void Get_data_csv_file_size()//of the data csv
{
if(Logging_UART_SD_CARD == true){NRF_LOG_INFO("\r\n Listing directory: /");}
ff_result = f_opendir(&dir, "/");
if (ff_result)
{
if(Logging_UART_SD_CARD == true){NRF_LOG_INFO("Directory listing failed!");}
}
do
{
ff_result = f_readdir(&dir, &fno);
if (ff_result != FR_OK)
{
if(Logging_UART_SD_CARD == true){NRF_LOG_INFO("Directory read failed.");}
}
if (fno.fname[0])
{
if (fno.fattrib & AM_DIR)
{
if(Logging_UART_SD_CARD == true){NRF_LOG_RAW_INFO(" <DIR> %s",(uint32_t)fno.fname);}
}
else
{
if(Logging_UART_SD_CARD == true){NRF_LOG_RAW_INFO("%9lu %s", fno.fsize, (uint32_t)fno.fname);}
if(strcmp((uint32_t)fno.fname, "data.csv")==0)//Convert both to a uint32_t
{
Size_of_file = fno.fsize;//Set the size of the file
//Does not get to here
}
}
}
}
while (fno.fname[0]);
}
Note this is programmed in C using a arm board. What operation do I need to do so I can get the file size?
I want something like:
if(fno.name == "data.csv")
{
Size_of_file = fno.fsize;//Set the size of the file
}

Just in case you determine using an implementation of stricmp() would be useful, here is one that I have used:
//case insensitive string compare
int cb_stricmp(const char *a, const char *b)
{
if(!a) return -1;
if(!b) return -1;
int ch_a = 0;
int ch_b = 0;
while ( ch_a != '\0' &&ch_a == ch_b)
{
ch_a = (unsigned char) *a++;
ch_b = (unsigned char) *b++;
ch_a = tolower(toupper(ch_a));
ch_b = tolower(toupper(ch_b));
}
return ch_a - ch_b;
}

Found a solution using snprintf neeeded to convert fno.fname to a string to compare the result.
char string_test[9] = "DATA.CSV";
char name_test[9]={0};
snprintf(name_test, sizeof(name_test),"%s",(uint32_t)fno.fname);
NRF_LOG_INFO("Result is: %s",name_test);
int result = strcmp(name_test, string_test);
if(result==0)//Convert both to a uint32_t
{
Size_of_file = fno.fsize;//Set the size of the file
NRF_LOG_INFO("Size of file using is: %9lu",Size_of_file);
}

Related

How to check existence of a directory in C

I have developed a program that is a simple file manager. For example, it lets a user create a file, delete a file, see the attribute of the files, change directory, and etc based on a CIFS path. However, I have found out a problem when I was implementing the cd command.
I have defined a global variable which will be initialized with a new path when I call FmCommandChangeDirectory. Now I wanted to check the existence of a directory/folder before I change the global working path to the new directory. I have implemented the following function but it has not able to find out a folder exists or not.
bool ChangePathRoot(const char* arg_computer_name)
{
strcpy_s(g_c_RootDrive, "C:\\");
strcpy_s(g_c_CurrentPath, "\\\\");
strcat(g_c_CurrentPath, arg_computer_name);
strcpy_s(g_c_ShareName, "\\C$");
strcat(g_c_CurrentPath, g_c_ShareName);
strcpy_s(g_c_SystemModifiablePath, "\\");
strcat(g_c_CurrentPath, g_c_SystemModifiablePath);
return true;
}
void ChangePathReverseBack(const char* arg_computer_name)
{
char c_PathBuffer[_MAX_PATH];
char c_Drive[_MAX_DRIVE];
char c_DirectoryMain[_MAX_DIR], c_DirectoryTemp[_MAX_DIR];
char c_Filename[_MAX_FNAME];
char c_Extension[_MAX_EXT];
strcpy(c_PathBuffer, g_c_CurrentPath);
_splitpath(c_PathBuffer, c_Drive, c_DirectoryMain, c_Filename, c_Extension);
_splitpath(c_PathBuffer, c_Drive, c_DirectoryTemp, c_Filename, c_Extension);
char* c_MainToken = strtok(c_DirectoryMain, "\\");
int i_StringsCounter = 0;
while (c_MainToken != NULL)
{
c_MainToken = strtok(NULL, "\\");
i_StringsCounter++;
}
char* c_TempToken = strtok(c_DirectoryTemp, "\\");
int i_StringsCounterTemp = i_StringsCounter - 1;
char c_FinalModifiedPath[MAX_PATH];
strcpy(c_FinalModifiedPath, "\\\\");
for (size_t i = 0; i < i_StringsCounterTemp; i++)
{
strcat(c_FinalModifiedPath, c_TempToken);
strcat(c_FinalModifiedPath, "\\");
c_TempToken = strtok(NULL, "\\");
}
char* c_TokenBase = NULL;
char* c_TokenDir = NULL;
c_TokenBase = strtok_s(c_FinalModifiedPath, "\\", &c_TokenDir);
char* c_TokenRoot = NULL;
char* c_TokenDirectory = NULL;
c_TokenRoot = strtok_s(c_TokenDir, "$", &c_TokenDirectory);
ChangePathSecondary(c_TokenRoot, arg_computer_name, c_TokenDirectory);
}
bool ChangePathRelative(const char* arg_directory)
{
strcat(g_c_SystemModifiablePath, arg_directory);
strcat(g_c_SystemModifiablePath, "\\");
strcat(g_c_CurrentPath, arg_directory);
strcat(g_c_CurrentPath, "\\");
return true;
}
void FmCommandChangeDirectory(const char* arg_computer_name)
{
char c_PathBuffer[_MAX_PATH];
char c_Drive[_MAX_DRIVE];
char c_DirectoryMain[_MAX_DIR];
char c_Filename[_MAX_FNAME];
char c_Extension[_MAX_EXT];
scanf_s("%s", c_PathBuffer, MAX_PATH - 1);
_splitpath(c_PathBuffer, c_Drive, c_DirectoryMain, c_Filename, c_Extension);
if (!strcmp(c_PathBuffer, "\\") || !strcmp(c_PathBuffer, "/"))
{
ChangePathRoot(arg_computer_name);
}
else if (!strcmp(c_PathBuffer, ".."))
{
ChangePathReverseBack(arg_computer_name);
}
else
{
ChangePathRelative(c_PathBuffer);
}
}
Now I wanted to implement a function that checks a path (directory) that has exist or not but I don't know how Can I Implement such function to check a directory has been existed or not.
There are two APIs for you to use:
In addition to GetFileAttributes mentioned by #IInspectable, you can also refer PathFileExists.
GetFileAttributes:
Retrieves file system attributes for a specified file or directory.
Code:
DWORD dwAttrib = GetFileAttributes(directorypath);
if(dwAttrib != INVALID_FILE_ATTRIBUTES &&(dwAttrib & FILE_ATTRIBUTE_DIRECTORY))
{
//exist
}
else
{
//not a vaild path
}
PathFileExists:
Determines whether a path to a file system object such as a file or
folder is valid.
Code:
BOOL retval = PathFileExists(directorypath);
if(retval == 1)
{
//file exists
}
else
{
//not a vaild file
}

Why does my program keep getting stuck while running the mandelbrot brainf*** program?

I wanted to improve my C skills, so I search some program's ideas.
Someone propose to create a simple Brainf*** interpreter and then a compiler. So here I am.
I created the interpreter and it works as expected, except with the Mandelbrot program:
A mandelbrot set fractal viewer in brainfuck written by Erik Bosman
+++++++++++++[->++>>>+++++>++>+<<<<<<]>>>>>++++++>--->>>>>>>>>>+++++++++++++++[[
>>>>>>>>>]+[<<<<<<<<<]>>>>>>>>>-]+[>>>>>>>>[-]>]<<<<<<<<<[<<<<<<<<<]>>>>>>>>[-]+
<<<<<<<+++++[-[->>>>>>>>>+<<<<<<<<<]>>>>>>>>>]>>>>>>>+>>>>>>>>>>>>>>>>>>>>>>>>>>
>+<<<<<<<<<<<<<<<<<[<<<<<<<<<]>>>[-]+[>>>>>>[>>>>>>>[-]>>]<<<<<<<<<[<<<<<<<<<]>>
>>>>>[-]+<<<<<<++++[-[->>>>>>>>>+<<<<<<<<<]>>>>>>>>>]>>>>>>+<<<<<<+++++++[-[->>>
>>>>>>+<<<<<<<<<]>>>>>>>>>]>>>>>>+<<<<<<<<<<<<<<<<[<<<<<<<<<]>>>[[-]>>>>>>[>>>>>
>>[-<<<<<<+>>>>>>]<<<<<<[->>>>>>+<<+<<<+<]>>>>>>>>]<<<<<<<<<[<<<<<<<<<]>>>>>>>>>
[>>>>>>>>[-<<<<<<<+>>>>>>>]<<<<<<<[->>>>>>>+<<+<<<+<<]>>>>>>>>]<<<<<<<<<[<<<<<<<
<<]>>>>>>>[-<<<<<<<+>>>>>>>]<<<<<<<[->>>>>>>+<<+<<<<<]>>>>>>>>>+++++++++++++++[[
>>>>>>>>>]+>[-]>[-]>[-]>[-]>[-]>[-]>[-]>[-]>[-]<<<<<<<<<[<<<<<<<<<]>>>>>>>>>-]+[
>+>>>>>>>>]<<<<<<<<<[<<<<<<<<<]>>>>>>>>>[>->>>>[-<<<<+>>>>]<<<<[->>>>+<<<<<[->>[
-<<+>>]<<[->>+>>+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[<<<<<<<<<]>>>>[-]<<<++++
+[-[->>>>>>>>>+<<<<<<<<<]>>>>>>>>>]>>>>>->>>>>>>>>>>>>>>>>>>>>>>>>>>-<<<<<<[<<<<
<<<<<]]>>>]
I don't understand why, but my program keeps getting stuck in some sort of endless loop. I try to debug it using gdb but it's hard to find the right breakpoint in order to see why it stuck.
The program is as follows:
#include <stdio.h>
#include <stdlib.h>
// Brainfuck instructions
// > Math stuff
#define INCR '+' // +1 on current MS
#define DECR '-' // -1 on current MS
// > Memory slot stuff
#define FORW '>' // Go to next MS
#define BACK '<' // Go to previous MS
// > Logic stuff
#define SJMP '[' // Loop till current MS value is equal to zero
#define EJMP ']' // Jump to the beginning of the loop
// > I/O stuff
#define PRTC '.' // Print character with MS value as ASCII code
#define GETC ',' // Get an user input ASCII character code
typedef unsigned char byte;
// The brainfuck program struct
typedef struct {
byte *values;
int size;
int index;
byte *loops_starts;
int loop_size;
int loop_index;
} BrainfuckProgram;
void initialize(BrainfuckProgram *bfp) {
bfp->values = malloc(bfp->size * sizeof(*bfp->values));
bfp->loops_starts = malloc(bfp->size * sizeof(*bfp->loops_starts));
}
int allocate_values(BrainfuckProgram *bfp) {
byte *newMem = realloc(bfp->values, bfp->size * sizeof(byte));
if (!newMem) {
return 1;
}
bfp->values = newMem;
return 0;
}
int allocate_new_loop(BrainfuckProgram *bfp) {
byte *newMem = realloc(bfp->loops_starts, bfp->loop_size * sizeof(byte));
if (!newMem) {
return 1;
}
bfp->loops_starts = newMem;
return 0;
}
void set_value(BrainfuckProgram *bfp, byte value) {
int tempValue = value < 0 ? 255: value % 256;
*(bfp->values + bfp->index) = tempValue;
}
int get_value(BrainfuckProgram *bfp) {
return *(bfp->values + bfp->index);
}
// FILE functions
int get_file_name(int argc, char *argv[], char** fname) {
if (argc == 1) {
printf("File name is missing\n");
return 1;
}
*fname = argv[1];
return 0;
}
int get_file_size(FILE *file) {
fseek(file, 0L, SEEK_END);
int size = ftell(file);
rewind(file);
return size;
}
// Main function
int main(int argc, char *argv[]) {
// Vector part
BrainfuckProgram bfp = {
.values = NULL,
.size = 1,
.index = 0,
.loops_starts = NULL,
.loop_index = 0,
.loop_size = 0
};
initialize(&bfp);
// FILE Part
char* fname = NULL;
int error = get_file_name(argc, argv, &fname);
if (error) {
goto exit;
}
// Create file variable
FILE *fin = NULL;
fin = fopen(fname, "r");
int size = get_file_size(fin);
// Create a char array of the right size
byte *prog = NULL;
prog = malloc(size * sizeof(*prog));
// Read 1 byte size times
fread(prog, 1, size, fin);
for (int i = 0; i < size; i++) {
byte current = *(prog+i);
switch (current) {
case INCR:
set_value(&bfp, get_value(&bfp) + 1);
break;
case DECR:
set_value(&bfp, get_value(&bfp) - 1);
break;
case FORW:
// if index+1 == size then we are at the
// last element of the vector cause
// size = index - 1
if (bfp.index+1 == bfp.size) {
bfp.size++;
int error = allocate_values(&bfp);
if (error) {
printf("an error occured while forwarding pointer");
goto close;
}
}
bfp.index++;
break;
case BACK:
// bfp.index == 0 then !bfp.index == true
if (!bfp.index) {
printf("can go back from index 0\n");
goto close;
}
bfp.index--;
break;
case SJMP:
if (bfp.loop_index == bfp.size) {
bfp.loop_size++;
int error = allocate_new_loop(&bfp);
if (error) {
printf("an error occured while forwarding pointer");
goto close;
}
}
bfp.loop_index++;
*(bfp.loops_starts + bfp.loop_index) = i;
break;
case EJMP:
if (bfp.loop_index == -1) {
printf("cannot go back");
goto close;
}
if (get_value(&bfp) != 0) {
i = *(bfp.loops_starts + bfp.loop_index);
} else {
bfp.loop_index--;
}
break;
case PRTC:
printf("%c", get_value(&bfp));
break;
case GETC:
; // Semicolon here because of the label error
byte buf;
scanf("%c", &buf);
set_value(&bfp, buf);
break;
}
}
close:
fclose(fin);
exit:
;
return 0;
}
I'd like to have some C related advice on what I have done wrong too.
The Mandelbrot program takes a decent time to run on a good interpreter. Yours, well, it isn't that good. That's why it "hangs" at the start.
Some good ideas that you had, performance-wise:
precalculating loops
Some bad ideas, performance-wise:
Using abstracted allocation functions instead of calling realloc
using scanf and printf instead of getchar and putchar
Some odd things that you did:
Manually truncating an unsigned char when wraparound is implicit
checking if an unsigned char is less than 0
using *(x + y) syntax instead of array indexing x[y]
I don't think you actually use those precalculated loops, if you do then probably not correctly
You also probably create a new precalculated loop every time you go over the loop again
Using the get_value and set_value functions instead of pointers (this will be a performance issue if you don't compile with optimizations)
A couple suggestions:
Try to avoid calling functions when you don't need to as much as possible.
Write a BrainFuck->C compiler using this reference.
On second thought, maybe you should try to debug this program instead.
You may also use my interpreter as a reference if you're OK with GPLv3. Note that it doesn't precalculate loops.

Segmentation fault:11, code works on windows but not mac

This function should print out a textual representation of the bytes in the file called filename. It worked on windows, but gives a segmentation fault: 11 on mac, thanks for any help
int hexdump(FILE *streaminput, FILE *streamoutput)
{
unsigned char buffer[8];
int bytescount;
int n = 0;
streaminput=fopen(filename, "rb");//read binary file
setvbuf(streaminput,NULL,_IOFBF,1024);//Buffer size to 1024 bytes
if(streaminput==0)
{
printf("cannot open file");
return 0;
}
for (;;)//read to the end of file,end feof(stream)!=0//
{
bytescount=fread(buffer,1,8,streaminput);//fread(void *buffer,
size_t size, size_t count, FILE * stream)//
//dec2hex(n, buf);//
if (bytescount==0)
{
fprintf(streamoutput,"%07X",n);
break;
}
fprintf(streamoutput,"%07X",n);
for(int i=0;i<bytescount;i++)
{
if(((char)buffer[i] >= 32) && ((char)buffer[i] <= 126))
{
//fprintf(streamoutput," %02x%c ",buffer[i],buffer[i]);
printf(" %02X %c ",buffer[i],buffer[i]);
//printf("%c",isprint(buffer[i]),buffer[i]);//
}
else
{
printf(" %02X . ",buffer[i],buffer[i]);
}
}
printf("\n");
n = n+bytescount;
if (bytescount <8)
{
fprintf(streamoutput,"%07X",n);
break;
}
}
fclose(streaminput);
streaminput=NULL;
return 0;
}
i guess your problem is with path the path you give in windows is like
C:\Users\Name\b.txt
but in linux and mac is something like
/home/name/b.txt
it's recommended to use relative path and use file separator
inline char separator()
{
#ifdef _WIN32
return '\\';
#else
return '/';
#endif
}

Arduino SD -> File extension

I found this example to list all files on the SD Card:
void printDirectory(File dir, int numTabs) {
while(true) {
File entry = dir.openNextFile();
if (! entry) {
// no more files
//Serial.println("**nomorefiles**");
break;
}
for (uint8_t i=0; i<numTabs; i++) {
Serial.print('\t');
}
if (entry.type
Serial.print(entry.name());
if (entry.isDirectory()) {
Serial.println("/");
printDirectory(entry, numTabs+1);
} else {
// files have sizes, directories do not
Serial.print("\t\t");
Serial.println(entry.size(), DEC);
}
}
}
But I want to list only the files with an explicit extension and save them into an array. Any one of you an Idea? I can't found any Function to get the file extension by the SD Class.
Unfortunately you will need to loop through each of the filenames individually.
please look at an example of my code that does just this. Similar to the above comment by "A Person".
Here are links to my actual use WHERE I use it and THE filter function
Note that my above use is using the SdFatLib, a more advanced version that SD (the IDE provided) library. Below I have adapted the same function for SD. Should work as it merely inspects the pointed char arrary's last 4 characters.
FYI - Note that the SD and SdFatLib only support 8.3 format.
void printDirectory(File dir, int numTabs) {
while(true) {
File entry = dir.openNextFile();
if (! entry) {
// no more files
break;
}
for (uint8_t i=0; i<numTabs; i++) {
Serial.print('\t');
}
if ( isFnMusic(entry.name()) ) { // Here is the magic
Serial.print(entry.name());
}
if (entry.isDirectory()) { // Dir's will print regardless, you may want to exclude these
Serial.print(entry.name());
Serial.println("/");
printDirectory(entry, numTabs+1);
} else {
// files have sizes, directories do not
Serial.print("\t\t");
Serial.println(entry.size(), DEC);
}
entry.close();
}
}
bool isFnMusic(char* filename) {
int8_t len = strlen(filename);
bool result;
if ( strstr(strlwr(filename + (len - 4)), ".mp3")
|| strstr(strlwr(filename + (len - 4)), ".aac")
|| strstr(strlwr(filename + (len - 4)), ".wma")
|| strstr(strlwr(filename + (len - 4)), ".wav")
|| strstr(strlwr(filename + (len - 4)), ".fla")
|| strstr(strlwr(filename + (len - 4)), ".mid")
// and anything else you want
) {
result = true;
} else {
result = false;
}
return result;
}

FreeImage include in c

Is there any way to include http://freeimage.sourceforge.net/index.html in my c test program without first installing the library? It fails to compile because of some memset..
Here is my C code. Is there any way to make it work? Please try compiling it and tell me how to do it if it works?
#define NAZIV_DATOTEKE 50
#include <stdio.h>
#include "FreeImage.h"
void FreeImageErrorHandler(FREE_IMAGE_FORMAT fif, const char *message);
FIBITMAP* GenericLoader(const char* lpszPathName, int flag);
int main(){
FreeImage_Initialise();
FIBITMAP *dib, *ptr;
char ulaz_slika[NAZIV_DATOTEKE] = "bmp_24.bmp";
char izlaz_slika[NAZIV_DATOTEKE] = "free.bmp"; //podrazumevana vrednost
dib = GenericLoader(ulaz_slika, 0);
//slika = FreeImage_Load(FIF_BMP, "bmp_24.bmp", BMP_DEFAULT);
FreeImage_SetOutputMessage(FreeImageErrorHandler);
if (dib) {
printf("Ucitan \"%s\".\n", ulaz_slika);
}
FREE_IMAGE_FORMAT fif = FreeImage_GetFileType(ulaz_slika, 0);
if ((fif != FIF_BMP) && (fif != FIF_ICO) && (fif != FIF_JPEG) && (fif != FIF_PNG) && (fif != FIF_TIFF)){
printf("Format slike nije podrzan.\n");
return 1;
}
ptr = FreeImage_ConvertTo24Bits(dib);
FreeImage_SetOutputMessage(FreeImageErrorHandler);
FreeImage_Unload(dib);
FreeImage_SetOutputMessage(FreeImageErrorHandler);
dib = ptr;
if (dib) {
printf("Konvertovan u RGB.\n");
}
const char *slika = (const char*)FreeImage_GetBits(dib);
if (FreeImage_Save(fif, dib, izlaz_slika, BMP_DEFAULT)) {
printf("Snimljen \"%s\".\n", izlaz_slika);
}
if (dib) {
FreeImage_Unload(dib);
}
FreeImage_DeInitialise();
return 0;
}
void FreeImageErrorHandler(FREE_IMAGE_FORMAT fif, const char *message){
printf("\n*** ");
if(fif != FIF_UNKNOWN) {
if (FreeImage_GetFormatFromFIF(fif))
printf("%s Format\n", FreeImage_GetFormatFromFIF(fif));
}
printf(message);
printf(" ***\n");
}
FIBITMAP* GenericLoader(const char* lpszPathName, int flag) {
FREE_IMAGE_FORMAT fif = FIF_UNKNOWN;
// check the file signature and deduce its format
// (the second argument is currently not used by FreeImage)
fif = FreeImage_GetFileType(lpszPathName, 0);
if(fif == FIF_UNKNOWN) {
// no signature ?
// try to guess the file format from the file extension
fif = FreeImage_GetFIFFromFilename(lpszPathName);
}
// check that the plugin has reading capabilities ...
if((fif != FIF_UNKNOWN) && FreeImage_FIFSupportsReading(fif)) {
// ok, let's load the file
FIBITMAP *dib = FreeImage_Load(fif, lpszPathName, flag);
// unless a bad file format, we are done !
return dib;
}
return NULL;
}
No you cannot. To compile your source, the linker needs the library.

Resources