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

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
}

Related

Fatfs string comparison for fno.fname

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);
}

The Code doesn't print the expected output, why?

The following code doesn't behave as expected ..
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdbool.h>
struct dest
{
char filename[20], keyword[20];
bool opened;
FILE * file;
};
void display_data(const struct dest p) {
printf("Keyword: %s, Filename: %s, Used: %s\n", p.keyword, p.filename, p.opened ? "Yes" : "No");
}
int main(int argc, char const *argv[])
{
// declaring variables
float lon, lat;
char info[80];
FILE *reader;
// checking required arguments
if ((argc+1) % 2 || argc < 2) {
fprintf(stderr, "Usage: %s file_to_read file_for_unknown type file type file ...\n", argv[0]);
return 2;
}
// opening the reader
if (!(reader = fopen(argv[1], "r"))) {
fprintf(stderr, "File can't be accessed: %s\n", argv[1]);
return 2;
}
// creating important globals
const short pairs = (argc-3)/2;
struct dest data[pairs];
struct dest other;
strcpy(other.filename, argv[2]);
other.opened = false;
// gathering data
short times = 4;
for(short i = 4; i < argc; i += 2) {
data[i-times].opened = false;
strcpy(data[i-times].keyword, argv[i-1]);
strcpy(data[i-times].filename, argv[i]);
times += 1;
}
// finally, scanning the file ..
struct dest *use_f; // pointer for the wanted destination ..
bool known;
while (fscanf(reader, "%f,%f,%79[^\n]", &lat, &lon, info)) {
// deciding which file to use ..
known = false;
for(short i=0; i < pairs; ++i) {
if (strstr(info, data[i].keyword)) {
known = true;
use_f = &data[i];
}
}
if (!(known)) {
use_f = &other;
}
// checking the file ..
if (!((*use_f).opened)) {
(*use_f).file = fopen((*use_f).filename, "w");
(*use_f).opened = true;
}
// writing to the file ..
fprintf((*use_f).file, "%f,%f,%s\n", lat, lon, info);
}
// closing all data streams, and informing user ..
for (short i=0; i < pairs; ++i) {
display_data(data[i]);
if (data[i].opened) {
fclose(data[i].file);
data[i].opened = false;
}
}
fclose(reader);
fclose(other.file);
return 0;
}
The command used to run it is this ..
./categorize spooky.csv other.csv UFO UFOS.csv # I get no output at all
It seems that the while loop doesn't actually end, which is mysterious, because the file (spooky.csv) is only 11 lines !
30.685163,-68.137207,Type=Yeti
28.304380,-74.575195,Type=UFO
29.132971,-71.136475,Type=Ship
28.343065,-62.753906,Type=Elvis
27.868217,-68.005371,Type=Goatsucker
30.496017,-73.333740,Type=Disappearance
26.224447,-71.477051,Type=UFO
29.401320,-66.027832,Type=Ship
37.879536,-69.477539,Type=Elvis
22.705256,-68.192139,Type=Elvis
27.166695,-87.484131,Type=Elvis
It just keeps writing to other.file, yet I don't know why ..
The program simply doesn't end, can anybody explain things to me ?
From the fscanf() manpage: "The value EOF is returned if an input failure occurs before any conversion (such as an end-of-file) occurs."
Here's a hint... EOF isn't equal to 0. Your while-loop never terminates.

Error with content being read out of file

Hello fellow programmers i am trying to understand what exactly is happening in this area of my code.
Problem: I read some contents into a file , then i am trying to read back the contents out of the file just to make sure its the right contents i had put into the file but it is not giving me the correct output, so i am a little confused here is the code(saved content as binary) :
typedef struct acc
{
int id_no;
int pin;
float bal;
}Acc;
int Crte_acc(FILE *flepss)
{
int i,cnt;
Acc user[1000];
cnt = 1000;
for (i=1;i<1000;i++)
{
cnt+=1;
user[i].id_no = cnt;
user[i].bal=1000;
user[i].pin=0000;
fwrite(&user[i].id_no,sizeof(int),1,flepss);
fwrite(&user[i].pin,sizeof(int),1,flepss);
fwrite(&user[i].bal,sizeof(int),1,flepss);
}
return fclose(flepss);
}
Yea so above is the code that takes a file pointer and a count to keep the id to increase by 1 ( 1001,1002 etc), bal and pin required that i set the var with those digits.So i am wondering whats the problem, this is the code of me displaying the contents.
void DisplyFile()
{
FILE *dfp;
int x;
Acc pruser[1000];
dfp = fopen("Account.dat","rb");
fseek(dfp,0,SEEK_SET);
while (1)
{
if(!feof(dfp))
{
for (x=1;x<1000;x++)
{
fread(&pruser[x].id_no,sizeof(pruser[x].id_no),1,dfp);
fread(&pruser[x].pin,sizeof(pruser[x].pin),1,dfp);
fread(&pruser[x].bal,sizeof(pruser[x].bal),1,dfp);
printf("%d ",pruser[x].id_no);
printf("%d ",pruser[x].pin);
printf("%.2f\n\n",pruser[x].bal);
}
}
else
{
break;
}
}
}
EDIT: By contents coming out wrong i mean , giving me garbage values as to show that my write to file was not saved.
The problem may come from a missing fclose or fopen...
There is almost nothing to do to build something that works.
Three things to check :
-Does a fopen correspond to a fclose ?
-Are opening types similar ? Are both "wb" and "rb" used ?
-Another point is fwrite(&user[i].bal,sizeof(int),1,flepss);...bla is a float. float and int may have the same sizeof, but...It is safer to assume that it is not always the case !
#include <stdio.h>
typedef struct acc
{
int id_no;
int pin;
float bal;
}Acc;
int Crte_acc()
{
FILE *flepss;
int i,cnt;
Acc user[10];
cnt = 1000;
flepss = fopen("Account.dat","wb");
for (i=1;i<10;i++)
{
cnt+=1;
user[i].id_no = cnt;
user[i].bal=10;
user[i].pin=0000;
fwrite(&user[i].id_no,sizeof(int),1,flepss);
fwrite(&user[i].pin,sizeof(int),1,flepss);
fwrite(&user[i].bal,sizeof(float),1,flepss);
}
return fclose(flepss);
}
void DisplyFile()
{
FILE *dfp;
int x;
Acc pruser[10];
dfp = fopen("Account.dat","rb");
fseek(dfp,0,SEEK_SET);
while (1)
{
if(!feof(dfp))
{
for (x=1;x<10;x++)
{
fread(&pruser[x].id_no,sizeof(pruser[x].id_no),1,dfp);
fread(&pruser[x].pin,sizeof(pruser[x].pin),1,dfp);
fread(&pruser[x].bal,sizeof(pruser[x].bal),1,dfp);
printf("%d ",pruser[x].id_no);
printf("%d ",pruser[x].pin);
printf("%.2f\n\n",pruser[x].bal);
}
}
else
{
break;
}
}
fclose(dfp);
}
int main()
{
Crte_acc();
printf("file printed\n");
DisplyFile();
printf("end file read 1\n");
DisplyFile();
printf("end file read 2\n");
return 0;
}
To compile : gcc main.c -o main
Bye,

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.

While Reading Section of a PE file, SetFilePointer does not works properly

Okay, what I was trying to do is to print all the data of a section of a PE executable:
#include<stdio.h>
#include<Windows.h>
int dth(int dec)
{
return 0;
}
int main()
{
IMAGE_NT_HEADERS peHead;
IMAGE_DOS_HEADER dosMZ;
IMAGE_SECTION_HEADER *secHead;
unsigned long d;
char file[]=".\\test.exe";
HANDLE host;
int i=0;
printf("\nScanning %s :-",file);
if((host=CreateFileA(file,GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL))==INVALID_HANDLE_VALUE)
{
printf("\nFile OPEN Error");
return 0;
}
if(!ReadFile(host,(void*)&dosMZ,sizeof(dosMZ),&d,NULL))
{
printf("\nRead Fail");
return 0;
}
if(!(dosMZ.e_magic==IMAGE_DOS_SIGNATURE))
{
printf("\nNot a Valid PE");
return 0;
}
printf("\nDos Signature Found");
SetFilePointer(host,dosMZ.e_lfanew,NULL,FILE_BEGIN);
if(!ReadFile(host,(void*)&peHead,sizeof(peHead),&d,NULL))
{
printf("\nRead Fail");
return 0;
}
if(!(peHead.Signature==IMAGE_NT_SIGNATURE))
{
printf("\nNot Valid PE");
return 0;
}
printf("\nPe Signature Found");
printf("\nMachine to be Executed on: %x ;Intelx86 for 0x14c",peHead.FileHeader.Machine);
printf("\nNumber of Sections : %d",peHead.FileHeader.NumberOfSections);
if(peHead.FileHeader.Characteristics==0x10f)
printf("\nCharachteristics : Executable File");
else
printf("\nCharachteristics : DLL File");
printf("\nReading Sections :");
printf("%d",peHead.OptionalHeader.SizeOfHeaders);
secHead=(IMAGE_SECTION_HEADER*)GlobalAlloc(GMEM_FIXED,sizeof(IMAGE_SECTION_HEADER)*peHead.FileHeader.NumberOfSections);
ReadFile(host,(void*)secHead,sizeof(IMAGE_SECTION_HEADER)*peHead.FileHeader.NumberOfSections,&d,NULL);
for(i=0;i<peHead.FileHeader.NumberOfSections;i++)
{
printf("\n Section Name : %s",secHead[i].Name);
printf("\n RVA : %x",secHead[i].VirtualAddress);
printf("\n Pointer to Raw Data : %x",secHead[i].PointerToRawData);
printf("\n Size of Data : %x",secHead[i].SizeOfRawData);
}
printf("\nPrinting opcodes of code Section:\n\n");
SetFilePointer(host,(int)secHead[1].PointerToRawData,NULL,FILE_BEGIN);
char ab;
for(i=0;i<=(secHead[1].SizeOfRawData);i++)
{
ReadFile(host,&ab,1,&d,NULL);
printf("%c",ab);
}
printf("%d\n,%d",i);
CloseHandle(host);
return 0;
}
The error happens when the setfilepointer sets the pointer to the start of .text section where it has to set the file pointer to 4096 location of file, instead it points to 16384 location. I discovered this after debugging the issue with ollydbg.
Anyoone can tell me whats wrong?

Resources