In memory Binary Search Vs. Disk based Binary Search - c++

In this program, I am reading "key.pc.db" file and printing its mid value.
#include <fstream>
#include <conio.h>
#include <stdio.h>
#include <time.h>
#include <sys/time.h>
#include <sys/stat.h>
using namespace std;
int main( int argc, char *argv[] )
{
ifstream fp;
int mval;
int sizek;
struct stat filek;
int min, max, mid;
if(stat("key.pc.db", &filek) ==0 )
sizek=filek.st_size;
sizek=sizek/sizeof(int);
min=0;
max=sizek-1;
mid=(min+max)/2;
printf("mid %d ",mid);
fp.open( "key.pc.db", ios::in | ios::binary );
fp.seekg(mid, ios::beg);
fp.read( (char *) &mval, (int) sizeof( int ) );
printf("%d mval ", mval);
getch();
return 1;
}
In this program also I am reading the same file but I am storing the value of the file in an array and then printing the mid value. The mid index for both the program shows the same but the value comes out to be different. Why so?
#include <fstream>
#include <conio.h>
#include <stdio.h>
#include <time.h>
#include <sys/time.h>
#include <sys/stat.h>
using namespace std;
int main( int argc, char *argv[] )
{
ifstream fp;
int index;
int sizek;
int kval;
struct stat filek;
int min, max, mid;
int i=0;
if(stat("key.pc.db", &filek) ==0 )
sizek=filek.st_size;
sizek=sizek/sizeof(int);
int k[sizek];
fp.open( "key.pc.db", ios::in | ios::binary );
fp.read( (char *) &kval, (int) sizeof( int ) );
while( !fp.eof() )
{
k[i++]=kval;
fp.read( (char *) &kval, (int) sizeof( int ) );
}
min=0;
max=sizek-1;
mid=(min+max)/2;
printf(" index %d ", mid);
printf(" kmid %d ", k[mid]);
getch();
return 1;
}

You're seeking to the wrong point in the file in the first case. You should be seeking to mid*sizeof(int) rather than mid.

Related

Linux: Is writeback related to number of files?

I am trying to do some experiments of pagecache and writeback mechanism on linux 5.4.81. I have set dirty_ratio to be 50, dirty_background_ratio 45, dirty_expire_centisecs 500000000, dirty_writeback_centisecs 500000000. When I write a big file of 250GB using write(), I can find that writeback begin to work when dirty_pages reach 45% of total memory, which is in line with expectation.
But when I write 125 small files of 2GB, the writeback begin to work when dirty_pages only reach about 25%. I wonder why this happen?
The total memory of my platform is 256G.
#include <stdio.h>
#include <string>
#include <sys/time.h>
#include <sstream>
#include <fstream>
#include <iostream>
#include <fcntl.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/stat.h>
using namespace std;
int main()
{
struct timeval start, end;
long long total_time = 0;
ofstream outfile("write_time.txt",ios::trunc);
int loop=1;
while(loop--){
for(int i=0; i<125; i++){
stringstream ss;
string num;
ss<<i;
ss>>num;
string a = "test";
string b = ".dat";
string fileName = a+num+b;
const char*tmp=fileName.c_str();
int fp = open(tmp,O_CREAT|O_RDWR,S_IRUSR|S_IWUSR);
// int fp = open(tmp,O_WRONLY|O_TRUNC);
int pos = 0;
char data[1024] = "ab\n";
gettimeofday( &start, NULL );
while (1)
{
write(fp, data, 1024);
pos++;
if (pos >= 2*1024*1024)
break;
}
gettimeofday( &end, NULL );
int timeuse = 1000000 * ( end.tv_sec - start.tv_sec ) + end.tv_usec - start.tv_usec;
printf("write_time: %d us\n", timeuse);
total_time +=timeuse;
outfile<<timeuse<<endl;
}
}
outfile<<total_time;
outfile.close();
return 0;
}

command spawnl() not executed

I have a code that is executable without error messages but it seems like it denies to run the code
I call by the "spawnl" command. This is my code and I receive "error=-1". I tried may different ways to solve the situation but I always receive the "-1" for an answer. I use Dev C++ compiler with 32bit release. My problem is to call the other program, sending the name of the file.
#include <stdlib.h>
#include <graphics.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <conio.h>
#include <process.h>
#include <ctype.h>
#include <dir.h>
#include <windows.h>
#include <dos.h>
#include <iostream>
#include <stddef.h>
void translate_to_ascii_files(),
save_mesh_data(),
make_no(),
give_names();
int load_patches(char *);
FILE *memco ;
int outnod[400] ;
float r_vector[21][21][3],cx[500],cy[500],cz[500] ;
int NOP1,NOP2; /* Number Of Points */
int patches;
char nams[26][26];
int num_of_files;
int kk,nv,nh,exnod,totnod ;
int no[4][400];
char filename[26];
void *buf;
COORD coord= {0,0};
HANDLE hConsole;
using namespace std; // std::cout, std::cin
void gotoxy(int x,int y) {
coord.X=x;
coord.Y=y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),coord);
}
int main(int argc,char *argv[]) {
char com_nam[26];
int counter1,counter2,i;
int error;
system("cls");
give_names();
printf("give the final filename:");scanf("%s",filename);
for(patches=1;patches<=num_of_files;patches++) {
strcpy(com_nam,nams[patches]);
load_patches(com_nam); /* load patches for meshing*/
i=1;
for(counter1=0;counter1<=NOP1;counter1++) {
for(counter2=0;counter2<=NOP2;counter2++) {
cx[i]=r_vector[counter1][counter2][0];
cy[i]=r_vector[counter1][counter2][1];
cz[i]=r_vector[counter1][counter2][2];
i=i+1;
}
}
nh=NOP1+1;nv=NOP2+1;
make_no();
save_mesh_data();
if(argc ==1){
error=spawnl(P_WAIT,"c:\\cpprog\\unitsrf.exe","",filename,NULL);
if (error ==0) {
else {printf ("error=%d\n",error); system("PAUSE");
} }
else{gotoxy(2,11);printf("error=%s\n\n",argv[1]);
system("PAUSE");
}
} translate_to_ascii_files();
}

Trim an audio file that is labelled with a timestamp c++

So i have a program that records snippets of audio on a microphone array, it then timestamps the end time of the file. My problem is that the process of the program starting the recording takes a random amount of time to start and so the audio is a random length. I want a way to read the size of the file (kilobytes) then trim the file by a certain number of kilobytes so that the recordings are always the same length.
#include <stdio.h>
#include <time.h>
#include <math.h>
#include <stdlib.h>
#include <chrono>
#include <thread>
#include<signal.h>
#include<unistd.h>
#include <sys/time.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include "zlib.h"
long long int rem;
long long int ms1;
long long int unixtime;
using namespace std;
const char* Filenames;
int main(void) {
int system(const char *command);
int x;
struct timeval tp1;
rem = 5;
while (rem != 0) {
gettimeofday(&tp1, NULL);
ms1 = tp1.tv_sec * 1000ll + tp1.tv_usec / 1000ll;
rem = ms1 % 10000;
}
for (x=0; x<3; x++){
pid_t pid=fork();
if (pid==0){
execl("/home/pi/odas/bin/odaslive", "/home/pi/odas/bin/odaslive", "-vc", "/home/pi/odas/config/odaslive/matrix_creator.cfg", (char *)NULL);
exit(127);
} else {
std::this_thread::sleep_for(std::chrono::milliseconds(15000));
kill(pid, SIGINT);
}
gettimeofday(&tp1, NULL);
unixtime = tp1.tv_sec + tp1.tv_usec / 1000000ll;
std::string name1 = "/home/pi/matrix_creator_explore/postfiltered/postfiltered1_";
std::string name2 = ".raw";
std::string result1;
result1 = name1 + std::to_string(unixtime) + name2;
const char *cstr = result1.c_str();
rename ("/home/pi/matrix_creator_explore/postfiltered.raw", cstr);
std::string name3 = "/home/pi/matrix_creator_explore/tracked/tracked1_";
std::string name4 = ".raw";
std::string result2;
result2 = name3 + std::to_string(unixtime) + name4;
const char *cstr1 = result2.c_str();
rename ("/home/pi/matrix_creator_explore/tracked.raw", cstr1);
struct stat buf;
stat( cstr,&buf);
printf ("\n %i \n", buf.st_size);
}
}

Error on call to shmat

Try to do something with shared memory by turning a chunk of user buffer into a shared memory, but the shmat() keep failing.
# ./a.out
shmid=89260087 0x7fbab055c000
shmat failed: : Invalid argument
Here is the source code. Wonder what's the reason. Thanks.
#include <arpa/inet.h>
#include <string.h>
#include <stdlib.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/shm.h>
#include <malloc.h>
char *output;
int n;
int main (int argc, char *argv[]) {
void *p = NULL;
int i;
double startTS;
double tmp;
output = (char*) valloc(0x1000000);
sprintf(output, "hi you!!");
unsigned int size = 0x1000000;
int shmid = shmget(12348, 0x1000000, IPC_CREAT); //SHM_RDONLY);
printf("shmid=%d %p\n", shmid, &output[0]);
char *bigBuf = (char*)shmat(shmid, &output[0], 0);
if (bigBuf == (void*)-1) {
perror("shmat failed: "); exit(-1);
}
bigBuf[0] = 'x';
printf("%p enter:\n", bigBuf);
scanf("%d\n", &i);
return 0;
}

Setenv: Type expression list treated as compound expression in initializer

Getting Type expression list treated as compound expression in initializer
On both these function calls -
char itoa(new_total, new_total_ch, 10);
int setenv("COUNT_TOTAL", new_total_ch, 1);
Here's the code snippet -
#include <iostream>
// create process team
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <ctime>
// initialize & process
#include <time.h>
#include <string>
#include <fstream>
#include <cmath>
#include <iosfwd>
// initialize & process
using std::ifstream;
using namespace std;
class Count3sProcessParallel {
public:
//int process();
int pr_count;
int process();
typedef int COUNT_TOTAL;
private:
int worker;
//declare process()
long unit_of_work;
long lower_bound;
long upper_bound;
int pr_i;
char * ct;
int ct_i;
int new_total;
char itoa();
char * new_total_ch;
int setenv();
};
int Count3sProcessParallel::process() {
// determine upper lower bounds
unit_of_work = in_length/workers_num;
lower_bound = (worker -1) * unit_of_work;
upper_bound = (worker * unit_of_work) -1;
// iterate and count
pr_count = 0;
for (pr_i = lower_bound; pr_i < upper_bound; pr_i++)
if (floor(in_buffer[pr_i] == 3))
pr_count++;
return pr_count;
//update COUNT_TOTAL
ct = getenv("COUNT_TOTAL");
ct_i = atoi(ct);
new_total = (pr_count + ct_i);
char * new_total_ch[33];
char itoa(new_total, new_total_ch, 10);
int setenv("COUNT_TOTAL", new_total_ch, 1);
delete[] in_buffer;
return 0;
}
How do I resolve this? Thanks.
Remove the leading types. Just use:
itoa(new_total, new_total_ch, 10);
setenv("COUNT_TOTAL", new_total_ch, 1);