Thursday, October 15, 2009

How to read Binary Data File in C (Sequentially)

Exactly two lines have to be changed from ASCII file mode given here.
Differences from ASCII mode:
1 - Additional "b" for fopen()
2 - Usage of fread() instate of fscanf
*/
...
fp = fopen(i_filename, "rb"); // read a binary file ("r" and "b")
...
/* loop until all data keep into array */

while( (!feof(fp))){
//fscanf(fp, "%f", &value); you can not use this any more for binary files. Now you have have to use fread()
fread(&value, sizeof(FP32), 1, fp);
...
}

Labels: , ,

Tuesday, July 28, 2009

How to read (ASCII) data file in C

/*Function that reads the data file into an array and returns a pointer that points to this array of FP32*/

FP32* readData(const char *i_filename){

FILE *fp;
fp = fopen(i_filename, "r"); //open file , read only
INT32U numElements = 0;
FP32 value; //keep value at pointer position
FP32 *array=NULL; //set to NULL because of realloc
/* loop until all data keep into array */

while( (!feof(fp))){
fscanf(fp, "%f", &value);
array = (FP32 *) realloc (array,(numElements+1) * sizeof(FP32 *));
array[numElements++] = value;
}
/* shift array and add "size of array" to its first element
since there is no way to get size of an array from its FP32 pointer*/

INT32U i;
array = (FP32 *) realloc (array,(numElements+1) * sizeof(FP32 *));
for(i=numElements;i>0;i--){
array[i]=array[i-1];
}
array[0]=numElements;
/* close file */
fclose(fp);
return array;
}

Labels: , ,

Thursday, December 21, 2006

Inline in C++

The double vector sorting and addition functions are defined as inline using the inline keyword.

Code:
//MyMath.h
inline int sort_vector_inline_new(vector<double>& v){ //new inline
sort(v.begin(),v.end());
return 1;
}
inline int add_inline_new(int a,int b){
return a+b;
}


Result:(Speed test)

Labels: , ,

Inline Function in C++ (vector sorting speed test)

Now it differs from addition...
"double" vector sorting with class defined function is faster than inline function defined in header file. See the below test.

Test:
Copy and paste the below codes to your previous test project files to add vector sorting capability.
İf you want, change the name of the class "Add" in "MyMath.h". Since it contains also sort() function now
Do not forget to include "vector" and "algortihm" for dealing with vector and its sort() method.
Here is the additional includes for changed files
#include
"vector"
#include
"algorithm"
//put this code to "MyMath.h" int sort_vector_inline(vector<double>& v){ //defined inline sort(v.begin(),v.end()); return 1; }
int sort_vector_class_def(vector<double>& v);

===============================================

//put this code to "class_def.cpp" int sort_vector_class_def(vector<double>& v){ //defined inline sort(v.begin(),v.end()); return 1; }


===============================================

//All of Main.cpp is given here.(lots of changes). //Filename:Main.cpp
#include "MyMath.h"
#include "stdafx.h"
#include
"vector"
#include
"algorithm"

using namespace std;
void main()
{
DWORD startTime,endTime,difTime;
vector v,v1;
int a=1;
int b=2;
int c;
Add testAdd;

cout<<"double vector sorting..."<<"\n";

//fill vector with random numbers
for(int j=0;j<1e7;j++){
v1.push_back(rand());
}
startTime=GetTickCount();
testAdd.sort_vector_inline(v1);
endTime=GetTickCount();
difTime=endTime-startTime;
cout<< "it took "<
//fill vector again since sorted vector sorting is much more faster

for(int j=0;j<1e7;j++){
v.push_back(rand());
}
startTime=GetTickCount();
testAdd.sort_vector_class_def(v);
endTime=GetTickCount();
difTime=endTime-startTime;
cout<< "it took "<
cout<<"addition..."<<"\n";

//use function defined in other cpp file
startTime=GetTickCount();
for(int i=0;i<1e9;i++){
c=testAdd.add_class_def(a,b);
}
endTime=GetTickCount();
difTime=endTime-startTime;
cout<< "it took "<startTime=GetTickCount();
for(int i=0;i<1e9;i++){ style="color: rgb(0, 0, 0);"> c=testAdd.add_inline(a,b);
}
endTime=GetTickCount();
difTime=endTime-startTime;
cout<< "it took "<}

===============================================


I changed the order of functions in main file to see if there is a difference in speed.
It is same for the addition. Still inline function works faster.
Let's see what happened for vector sorting (below pictures).



if you change the order of function calling sequence, inline function for vector sorting works faster.
So we could not say anything about speeds yet.


Labels: , ,

Inline Function in C++

... .However, another good reason to inline is that you can sometimes speed up your program by inlining the right function. Instead of calling the function every time it is invoked, the compiler will replace the function call with a copy of the function body.
[from the page given in the link. Also read Why not inline everything?]

And here is my project for speed comparison of inline defined function and class defined function in Visual C++:

First: Copy and paste below codes with the correct name into header files in your project.

//Filename:MyMath.h
#include

using namespace std;

class Add{
public:
int add_inline( int a,int b){
return a+b;
}
int add_class_def(int a1,int b1);
};

========================================================

// Filename:stdafx.h
// include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// This source code is only intended as a supplement to the
// Microsoft Classes Reference and related electronic
// documentation provided with the library.
// See these sources for detailed information regarding the
// Microsoft C++ Libraries products.
#pragma once
#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
// turns off ATL's hiding of some common and often safely ignored warning messages
#define _ATL_ALL_WARNINGS
#ifndef _WIN32_WINNT
#define _WIN32_WINNT 0x0403
#endif
// TODO: this disables support for registering COM objects
// exported by this project since the project contains no
// COM objects or typelib. If you wish to export COM objects
// from this project, add a typelib and remove this line

#define _ATL_NO_COM_SUPPORT
#include

Second: Below codes are the cpp files for your project.

//Filename:Main.cpp
#include "MyMath.h"
#include "stdafx.h"
#include

using namespace std;
void main()
{
DWORD startTime,endTime,difTime;

int a=1;
int
b=2;
int c;
Add testAdd;
// use inline function declared and defined in header file MyMath.h
startTime=GetTickCount();
for(int i=0;i<1e9;i++){>
c=testAdd.add_inline(a,b);
}
endTime=GetTickCount();
difTime=endTime-startTime;
cout<< "it took "<<<">
//use function defined in other cpp file
startTime=GetTickCount();
for(int i=0;i<1e9;i++){
c=testAdd.add_class_def(a,b);
}
endTime=GetTickCount();
difTime=endTime-startTime;
cout<< "it took "<<<">
}
========================================================

//File name:class_def.cpp
#include "MyMath.h"
int Add::add_class_def(int a1,int b1){
return a1+b1;
}

========================================================


// Filename: stdafx.cpp
// stdafx.cpp : source file that includes just the standard includes
// PerformanceCounter.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// This source code is only intended as a supplement to the
// Microsoft Classes Reference and related electronic
// documentation provided with the library.
// See these sources for detailed information regarding the
// Microsoft C++ Libraries products.
#include "stdafx.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file


Results:
*test1


*test2 (In another computer with different configuration)

Labels: , ,

Thursday, December 14, 2006

Microsoft Visual C++ .NET'de "fstream" Kullanmak

Boş satırları "fstream" "0" olarak okuyor ve hataya sebep oluyor.
Eğer data dosyasında bir satır sonunda "enter" a basılırsa data dosyası okurken bu kısımlar "0" okunur ve data saklanan yapıya 0 gönderilir. Bu durumdan haberdar değilseniz hatanın nerede olduğunu bulmak oldukça zorlaşır.
Debug yapıp bulurum derseniz de başınız dertte demektir.
En son debug yaparken breakpoint koyduğum yere 5 dak. 44 sn sonra gelebildi Microsoft Visual C++ .NET.
Dosyadan data okuduğunuz while loop unun içine yazılacak aşağıdaki if check i bu problemin oluşma ihtimalini ortadan kaldırır.


if(!isdigit(file_to_read.peek())) {
file_to_read.ignore();
continue;
}

Labels: , ,

Wednesday, December 06, 2006

sizeof an Array in C++

Do not hestitate to use the below code. Just gives the size of an array in C++. :)
double array = {1.0,2.0,3.0,4.0,5.0};
int size = sizeof array / sizeof array[0];
Altough it is too long to write (just for taking the size) and hard to understand what is calculated, this code gives the result as 5.

Labels: , ,