dimanche 19 avril 2015

Update file using fscanf and fprintf

I have tab seperated record like this in .txt file



1000 Aashir 0213-4211685 123456 0
1001 Muhammad Ali 0334-3387918 abcd 0
1002 Azam 0323-2143133 hassan123 0
1003 Taha Hashmi 0214-6589421 786 0
1004 Khan 03452145698 helloworld 0


now i want to update or modify these values using fscanf and fprintf


This is what I've tried so far but now i got stuck on how to write on a specific position



int update_record(Account* user)
{
FILE *record;
record=fopen("database.txt","a+");
char buffer[SIZE];Account req;
while(fgets(buffer,SIZE,record))
{
sscanf(buffer,"%d\t% [^\t]\t%s\t%s\t%ld\n",&req.acc_num,req.name,req.mobileno,req.pass,&req.acc_bal);

if(req.acc_num==user->acc_num)
break;
.
.
.
}


I am beginner please help, i have to use fscanf and fprintf only, #assignmentcriteria :(


Why the pattern of data appears in memory when I use `malloc()`?

I have a simple code:



#include <stdio.h>
#include <stdlib.h>

int main(void){
char *str = (char *) malloc(4*sizeof(char));
int i;
for(i = 0; i < 64; i ++)
printf("%d, %ld, %d, %c\n", i, (long) &(str[i]), (int) str[i], str[i]);
return 0;
}


I allocate a memory into str using malloc() which is available to save 4 letters in str[0], ..., str[3]. I know that malloc() does not initialize its memory while calloc() does.


This program prints str[i] with i, address of str[i], value of str[i], letter of str[i], in order. (I use 64-bits Ubuntu, hence address is long type.)


As expected, addresses are quite different for every time I run the program. But I wonder that why str[24], str[25], and str[26] are -31, 15, 2, repectively, and other values are all 0 as you can see below:


Ubuntu 12.04.5


(Note that without option -O0 gives same result.)


How can memory has same sequence (0,0,...,0,-31,15,2,0,0,...) even though only first four 0s in that sequence are allocated and others are out of care?


Is this a bug in the compiler or how C normally works?

I'm using the XC8 compiler which targets 8 bit microcontrollers.


This does not produce any warnings or errors, but hangs the microcontroller anyway:



uint8_t some_array[4];
uint8_t // no compile errors at all
some_function();


Another thing I've noticed, expect this one does not crash the microcontroller, and seems to return 0:



printf("%c", some_function);


In this one, I'm calling a function which never returns a 0. I've forgotten to add the () but it compiles and somehow runs anyway, but with a wrong return value.


Problems of input(scanf cin ) while running C/C++ with Textmate 2

I'm using Textmate2 as my coding editor.But what i found is that scanf in c or cin in c++ can't work in Textmate2.I googled for a while.And the solution seems to install a library into Textmate support path.The path can be located by running a shell command "echo "$TM_SUPPORT_PATH"".So i did it.Downloaded the tm_interactive_input.dyllb,copy it into the lib folder in the support path.Everything seems to be the same as the blog told me to do.However ,it still does work.I don't know why.The version of Textmate2 i'm using is Textmate2.0 beta 7.1,the latest version.Do i have any alternatives to fix this problem?


C - Login using file handling and linked list

I am creating an account using Create New Account option, & then writing the created username pwd to the file, but when I rerun the code & try to login using the same id, it fails. Using string compare, but it seems string is not being read.

struct user{ char username[10]; char password[10]; struct user *next; }*sUser,*pUser;



userlogin(void){
FILE *fp;
char uName[10], pwd[10];int i;char c;
sUser=pUser=(struct user *)malloc(sizeof(struct user));

printf("1. Login Through An Existing Account\n2. Create New account\n");
scanf("%d",& i);
system("cls");
switch(i){
case 1:
fp=fopen("user.dat", "w");
printf("Username: ");
scanf("%s",&uName);
printf("Password: ");
scanf("%s",&pwd);
fread (pUser, sizeof(struct user), 1, fp);
while(pUser!=NULL){
if(pUser->username==uName){
if(pUser->password==pwd){
accessUser();
}
}
pUser=pUser->next;
}
break;


case 2: do{ fp=fopen("user.dat", "r");
printf("Choose A Username: ");
scanf("%s",&pUser->username);
printf("Choose A Password: ");
scanf("%s",&pUser->password);
printf("Add another account? (Y/N): ");
fflush(stdin);
scanf("%c",&c);
if(c=='Y'||c=='y'){
pUser->next=(struct user*)malloc(sizeof(struct user));
}
}while(c=='Y'||c=='y');
pUser->next==NULL;
fwrite (sUser, sizeof(struct user), 1, fp);
break;
}
fclose(fp);
}


EDIT:

The value of pUser->username is not what it should be Can anyone tell me what I'm doing wrong.


Last child process not returning a value

I have tried to implement a Parallel Adder using processes. My problem is that among the child processes created, the last child process does not return a value. This error occurs when the no. of integers is an odd number and the number of child processes created is an even number


Here's my code :



#include <sys/ipc.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/shm.h>
#include <fcntl.h>
#include <errno.h>
#include <semaphore.h>
#include <unistd.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFFER_SIZE 200
#define BUFFER_SUB 2
typedef struct
{

int buff[BUFFER_SIZE];
sem_t mutex, empty, full;
}shared_data;

typedef struct
{
int subs[BUFFER_SUB];
sem_t mutex,empty,full;
}sub_totals;

int main(int argc, char** argv)
{

char *file_name = argv[1];
FILE *fp;
int number,i;
int j=0;
int num_values;
int k = atoi(argv[2]);


int segment_id;
size_t segment_size = sizeof(shared_data);
segment_id = shmget(IPC_PRIVATE,segment_size,IPC_CREAT|0666);
shared_data *shared_memory = shmat(segment_id,NULL,0);

int segment_id1;
size_t segment_size1 = sizeof(sub_totals);
segment_id1 = shmget(IPC_PRIVATE,segment_size1,IPC_CREAT|0666);
sub_totals *subtotal = shmat(segment_id1,NULL,0);

sem_init(&shared_memory->mutex,1,1);
sem_init(&shared_memory->empty,1,BUFFER_SIZE);
sem_init(&shared_memory->full,1,0);

sem_init(&subtotal->mutex,1,1);
sem_init(&subtotal->empty,1,BUFFER_SUB);
sem_init(&subtotal->full,1,0);
fp = fopen(file_name, "r");

while(fscanf(fp,"%d,",&number)!=EOF)
{
sem_wait(&shared_memory->empty);
sem_wait(&shared_memory->mutex);
shared_memory->buff[j] = number;
sem_post(&shared_memory->mutex);
sem_post(&shared_memory->full);
j++;
num_values=j;
}
int p, z;
int processes = k;
int temp_sub;
int count = 0;
int x;
int b;
int tot=0;
b = (num_values/processes);
double f = (num_values/(double)processes);

printf("%.11f\n", f);

if((num_values % 2) == 0)
{
b = b;
printf("%i\n", b);
}

else
{
//for(z = 1; z <= processes - 1; z++)
//{
b = (int)ceil(f + 0.5f);
//b = b - 1;
printf("%i\n", b);
//}

b = b - 1;
printf("%i\n", b);
}


for(i = 0; i < processes; i++)
{
int id;
temp_sub=0;
if((id=fork())==0)
{
for(x=(count*b);x<((count*b)+b);x++)
{
sem_wait(&shared_memory->full);
sem_wait(&shared_memory->mutex);
int num = shared_memory->buff[x];
sem_post(&shared_memory->mutex);
sem_post(&shared_memory->empty);
temp_sub = temp_sub + num;
}

int pid = getpid();
sem_wait(&subtotal->empty);
sem_wait(&subtotal->mutex);
subtotal->subs[0] = pid;
subtotal->subs[1] = temp_sub;
sem_post(&subtotal->mutex);
sem_post(&subtotal->full);

exit(0);
}
count++;
if(id>0)
{
int status;
wait(&status);
sem_wait(&subtotal->full);
sem_wait(&subtotal->mutex);
int pid = subtotal->subs[0];
int sub = subtotal->subs[1];
sem_post(&subtotal->mutex);
sem_post(&subtotal->empty);
printf("Sub total of process %d is %d\n",pid,sub);
tot = tot+sub;
}

}
printf("Total: %d\n",tot);
}


The file name with the integers are parsed as the first argument and the number of child processes as the second argument in command-line.


The file contains 1,1,2,3,4,4,5,6,10,11,14,17,25,16,5 integers. When the number of child processes parsed is 4, the following output should be returned :



Sub-total produced by Processor with ID x1: 7
Sub-total produced by Processor with ID x2: 19
Sub-total produced by Processor with ID x3: 52
Sub-total produced by Processor with ID x4: 46
Total: 124


The final process value and Total is not calculated. Please help. Thanks in advance.


How to pass some custom cookie parameters in fastcgi

I have written a server in fcgi and C and I need to add some custome parameter after I printed some String to request.out. to be clear this is my sample code:



while (1)
{
rc = FCGX_Accept_r(&request);
if (rc < 0)
break;
FCGX_FPrintF(request.out,
"Content-type: text/html\r\n"
"\r\n");
//the html page content
FCGX_FPrintF(request.out,
"<form method=\"post\" action=\"\">"
"<input type=\"text\" name=\"num\">"
"<input type=\"submit\" value=\"click\" name=\"submit\">"
"</form>"
);
.
.
.

//and somewhere like here I need to add a cookie parameter
FCGX_FPrintF(request.out,
"set-cookie:myParam=myValue\r\n"
"\r\n");
.
.
.
.
FCGX_Finish_r(&request);
}


but this ends up printing right to the page.


how can I put it to the start of the buffer?


Thanks for your help.


MPI program send probleme

i have tested this sample code of MPI that i found in a beginner MPI tutorial in a small grid architecture of 2 machines (vmware). but it dosn't seem to work, i don't have response, it keep freezing. this is the MPI code in C:



#include <mpi.h>
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char** argv) {
// Initialize the MPI environment
MPI_Init(NULL, NULL);
// Find out rank, size
int world_rank;
MPI_Comm_rank(MPI_COMM_WORLD, &world_rank);
int world_size;
MPI_Comm_size(MPI_COMM_WORLD, &world_size);

// We are assuming at least 2 processes for this task
if (world_size < 2) {
fprintf(stderr, "World size must be greater than 1 for %s\n", argv[0]);
MPI_Abort(MPI_COMM_WORLD, 1);
}

int number;
if (world_rank == 0) {
// If we are rank 0, set the number to -1 and send it to process 1
number = -1;
MPI_Send(&number, 1, MPI_INT, 1, 0, MPI_COMM_WORLD);
} else if (world_rank == 1) {
MPI_Recv(&number, 1, MPI_INT, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
printf("Process 1 received number %d from process 0\n", number);
}
MPI_Finalize();
}


i have ssh taht work in booth the 2 nodes without password, i modified the /etc/hosts to add the hostname and ip addresse of the 2 machines, i installed openmpi and hydra in my ubuntu machines,i have nfs shared directory where i put the files, but can't fix the probleme. when i execute the program in my locale machine, it work, but when i execute the pogram in parallel, it freez:



root@ubuntu1:/mirror# mpicc test1.c -o test1
root@ubuntu1:/mirror# mpiexec -n 2 ./test1
Process 1 received number -1 from process 0
root@ubuntu1:/mirror# mpiexec -n 2 -f 1 ./test1
^C
=====================================================================================
= BAD TERMINATION OF ONE OF YOUR APPLICATION PROCESSES
= EXIT CODE: 2
= CLEANING UP REMAINING PROCESSES
= YOU CAN IGNORE THE BELOW CLEANUP MESSAGES
=====================================================================================
APPLICATION TERMINATED WITH THE EXIT STRING: Interrupt (signal 2)
root@ubuntu1-virtual-machine:/mirror#


if you have any idea of the source of the problem, i would be very thankful.


What is the proper way to call multiple functions in C?

I am trying to write a program that will accept some integers and sort them, then display the list in ascending order. It will then check for adjacent triplets and display how many adjacent triplets there are.


The issue is that only the input function is being executed in main.


Could it be that the other functions should be voids? What is the "proper" way to call multiple functions in C?



#include <stdio.h>
int main()
{
input();
sort();
comparator();
output();
getchar();
getchar();
return 0;
}
int input()
{
int n, i, array1[30];
printf("Input the number of integers: ");
scanf("%d", &n, "\n");
printf("Input the integers: ");
for (i = 0; i = n; i++)
scanf("%d", &array1[i]);
return 0;
}
int sort(n, i, array1)
{
int a, b, *arrayS;
arrayS = &array1;
for (i = 1 ; i <= n - 1; i++)
a = i;
while ( a > 0 && arrayS[a] < arrayS[a-1])
b = arrayS[a];
arrayS[a] = arrayS[a-1];
arrayS[a-1] = b;
a--;
return 0;
}
int comparator(array2, n)
{
int i, AdjacentTriplets, one = 1, two = 2, three = 3;
int *arrayC = array2;
for (i = 0; i = n; i++)
if (arrayC[one] == arrayC[two] && arrayC[two] == arrayC[three])
AdjacentTriplets = 1;
else
AdjacentTriplets = AdjacentTriplets;
return 0;
}
int output(n, arrayC)
{
int A, *arrayO = arrayC;
for (A = 1; A =n; A++)
printf("%d The list is: ", arrayO[A]);
getchar();
getchar();
return 0;
}

Correction and tips for my code

I have added, modified the previous code. Now my problem is not getting the right layout. I realise arrays is better. BUT is there any way to fix it without arrays The text file is test0.txt as shown below



3 12867 1.0 2.0 1.0 5.0 4.0 5.0


5 15643 1.0 2.0 4.0 5.0 7.8 3.5 5.0 0.4 1.0 0.4


4 18674 1.0 0.4 0.4 0.4 0.4 3.6 1.0 3.6


0



The code is:



#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#define MAX_POINTS 100




double length(double x1,double x2,double y1,double y2);
double area_bits(double x1,double x2,double y1,double y2);



int
main(int argc,char *argv[]){
int npoints;
double x_point,y_point;
double x_prev=0,y_prev=0,x_first=0,y_first=0;
int poly_id;
int k,l,m=0;



double perimeter=0;
double area=0;
int primed=0;

/*Error check and echo-control*/
for(;m<=2;m++){

if(m==1){
printf("Stage 2\n");
printf("=======\n");
for(l=1;l<=5;l++){
printf("+-------");
}
printf("+\n");
printf("| id | nval | perim | area | eccen |\n");
for(l=1;l<=5;l++){
printf("+-------");
}
printf("+\n");
}
if(m==0){
printf("Stage 1\n");
printf("======\n");
}
while(scanf("%d %d",&npoints,&poly_id)==2){
if(npoints>MAX_POINTS){
printf("Exceeded limit\n");
exit(EXIT_FAILURE);

}
if(m==0){
printf("First polygon is %d\n",poly_id);
printf(" x_val y_val\n");

}

printf("| %5d | %5d |",poly_id,npoints);

perimeter=0;
area=0;
for(k=0;k<npoints;k++){
if (scanf("%lf %lf",&x_point,&y_point)==2){
if(m==0){
printf("%8.1f %8.1f\n",x_point,y_point);
}
if(k==0){
x_first=x_point;
y_first=y_point;
x_prev=x_point;
y_prev=y_point;

}
if(primed){
perimeter+=(length(x_point,x_prev,y_point,y_prev));
area+=area_bits(x_point,x_prev,y_point,y_prev);
x_prev=x_point;
y_prev=y_point;

}
primed=1;
}

}
perimeter+=length(x_first,x_prev,y_first,y_prev);
area+=area_bits(x_first,x_prev,y_first,y_prev);
if(m==0){
printf("perimeter = %.2f m\n",perimeter);
printf("area = %.2f m^2\n",area/2);
printf("eccentricity = %.2f\n",( pow(perimeter,2)/(area/2))/(4*M_PI));
}

printf("%6.2f |%6.2f |%6.2f |\n",perimeter,area/2,( pow(perimeter,2)/(area/2))/(4*M_PI));



}
if(m==1){
for(l=1;l<=5;l++){
printf("+-------");
}
printf("+\n");

}
}
return 0;
}

double length(double x1,double x2,double y1,double y2){
return sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));
}

double area_bits(double x1,double x2,double y1,double y2){
return (x1-x2)*(y1+y2);
}


The goal is to assign the first column to npoints,second to poly_id and third onwards to x_point and y_point.But each row has different number of x and y coords. I have a print a table for this as well, but that I can manage.


npoints determine the number of points(eg 3 npoints give 3 x_points and y_points).


So I type in to execute:



ass_1< test0.txt


The desired output:



Stage 1
=======
First polygon is 12867
x_val y_val
1.0 2.0
1.0 5.0
4.0 5.0
perimeter = 10.24 m
area = 4.50 m^2
eccentricity = 1.86

Stage 2
=======
+-------+-------+-------+-------+-------+
| id | nval | perim | area | eccen |
+-------+-------+-------+-------+-------+
| 12867 | 3 | 10.24 | 4.50 | 1.86 |
| 15643 | 5 | 18.11 | 19.59 | 1.33 |
| 18674 | 4 | 7.60 | 1.92 | 2.39 |
+-------+-------+-------+-------+-------+


Any corrections or tips is highly appreciated. Note that I am not looking for someone to tell me the answer, just guidance.


Thank You!


Getting the file-mode from the FILE struct?

I have a piece of C code, a function to be specific, which operates on a FILE*.


Depending on which mode the FILE* was opened with there are certain things I can and cannot do.


Is there any way I can obtain the mode the FILE* was opened with?


That FILE* is all the info I can rely on, because it is created somewhere else in the program and the actual file-name is long lost before it reaches my function, and this I cannot influence.


I would prefer a portable solution.


Running code from BSS section

In a buffer overflow attack, it's possible to run code from the BSS section (assuming the user disabled some security protections). How is code running there different than code running in the text section? Does it make sense to push things onto the stack while running code from the BSS section? If not, how can functions be called from there?


I'm using linux x86.


Should I abstract the Database API from Abstract Data Type representing a Employee in my HR Management System?

I am trying to apply some OOP principles to some C Abstract Data Type model. Given a ADT that abstract a Employee, where a Employee instance is inmutable (when instancing a Employee it gives a unique primary key Name and Last Name and this primary key keeps inmutable during the Employee object life) i wonder if this ADT should care about saving his data in the Database.


So given this piece of code of the ADT:



static char* address; //Address of the Employee

TakeNewAddress(char* newaddress)
{
.....
}

GiveAddress(char* address)
{
....
}


Should SetAddress method copy the content of newaddress into his address attribute and save it into Database or should it only update his address attribute? Should GiveAddress return address variable or should it retrieve it from the database?


I think this ADT representing a Employee should not care about internal database (it is not something you ask to a employee), so saving his data into the Database should be performed outside this ADT by a special handler or user interface for the system.


About the bubble sort in c

This is my code: //buble sort



#include<stdio.h>
int main(){
int a[11];
int temp;
int i,j;
//input

for(i=1;i<=10;i++){
scanf("%d",&a[i]);
}

//sort

for(i=1;i<10;i++){ //the number of number
for(j=1;j<10-i;j++) //--
if(a[j]<a[j+i]){
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}

//output
for(i=1;i<=10;i++){
printf("%d ",a[i]);
}

getchar();
getchar();
return 0;


}


but the result was not like what I think.the number before was 1 2 3 4 5 6 7 8 9 0 but after it was 8 6 5 4 3 7 2 9 1 0 thanks !


Segmentation Fault - Core Dumped in MergeSort Function

Can anyone provide insight as to why the following section of code would result in a segmentation fault (core dumped) error? I am sure I have a stray pointer or something; however, I cannot find it. Any help would be appreciated. I am trying to create a MergeSort function.



int* mergesort(int* num, int n)
{
int *left, *right;
int middle = n/2;

if (n <= 1)
return num;

//split array into two halves each with elements of 0...middle-1 and middle...n-1 correspondingly
split(num, n, &left, &right, middle);
left = mergesort(left, middle);
right = mergesort(right, n-middle);

merge(num, left, right, middle, n-middle);

free(left);
free(right);

return num;
}

void split( int* num, int n, int** left, int** right, int middle)
{

left = &num;
right = &num + middle;

}

int* merge (int* num, int* left, int* right, int sizeLeft, int sizeRight)
{
int i, j, k, n;
i = j = k = 0;
n = sizeLeft + sizeRight;

while (k < n)
{
if (i < sizeLeft)
{
if (j < sizeRight)
{
insert(num, left, right, &i, &j, &k);
}
else
{
append(num, left, sizeLeft, &i, &k);
}
}
else
{
append (num, right, sizeRight, &j, &k);
}
}
}

void insert(int* num, int* left, int* right, int* i, int* j, int*k)
{
if (left[*i] < right[*j])
{
num[*k] = left[*i];
(*i)++;
}
else
{
num[*k] = right[*j];
(*j)++;
}

(*k)++;
}

void append(int* num, int* half, int sizeHalf, int* i, int* k)
{
while (*i < sizeHalf)
{
num[*k] = half[*i];
(*i)++; (*k)++;
}
}

sscanf input not working

I have tab seperated records like this



1000 Muhammad Aashir 0213-4211685 123456 0


first I have read the line by using fgets and now i am trying to extract contents by using sscanf, but there is an unexpected problem... please help I am beginner


here is the code



char buffer[SIZE];Account req;
while(fgets(buffer,SIZE,fptr))
{
cout<<endl<<buffer<<endl;
sscanf(buffer,"%d\t%s\t%s\t%s\t%ld\n",&req.acc_num,req.name,req.mobileno,req.pass,&req.acc_bal);
cout<<endl<<req.pass;
}


output of BUFFER is same as the record line


but after extracting values, when I am displaying the 'req.pass' the value is incorrect


req.pass is displaying '0213-4211685' but it has to display '123456'


C Windows - Memory Mapped File - dynamic array within a shared struct

I'm trying to share a struct similar to the following example:



typedef struct {
int *a;
int b;
int c;
} example;


I'm trying to share this struct between processes, the problem that I find is that when I initialize 'a' with malloc, I won't be able to access the array from within the second process. Is it possible to add this dynamic array to the memory mapped file?


Accessing Embedded Linked Lists in C

Considering I have two structures. The first one represents a student :



typedef struct student

{
int code; // code of student
char* name;
note* list_note; // a list of his notes
struct* student next;

}


And the other one represents his notes :



typedef struct note

{

char* name // name of subject . eg:math
floate note // note at exam;
struct note* next;



}


The data file that contains information about students and their notes were stored on my computer and I was able to load them.


This is an example of the data file :



1300 david
programming 14
math 14
webmastering 18


Now I want to create a function that shows all the student who have all their notes higher than 12. I created the following code, that doesn't generate any error, but during execution it doesn't give me what I want.


Here is the code :



student* std=list_std;// list_std was declared in the functions that reads the data file and loads it;
note* nt=list_note;// list_note was declared in the functions that reads the data file and loads it;

while ( std)
{


while (nt )
{
if ( std->nt->note < 12)
{
break;
}
else
{
nt=nt->next
}
}

printf("%s",std->name);
std=std->next;
}

How to call printf in machine language

Let's say we have the assembly code that prints Z to the screen.



pushl $'Z'
call putchar
add $4, %esp


How can we write this in machine language code? I've checked both online resources and this code in gdb, but the former disagrees with the latter and the latter changes each time I run the code. Thank you for your help.


I'm using linux x86. Again, I'd like to say that I want to know how to write this in machine language code.


How can i convert this simple C function to python code [on hold]


#define SetBit(a, b) (((unsigned char *) a)[(b) >> 3] |= (1 << ((b) & 7)))

Piping data to Gnuplot from C

I've managed to create some code which will continuously send data points from a C program to gnuplot to show evolution of a time dependent Schrodinger equation. This is the function I've made which is iterated in a loop which updates the WF[] values each time: (Both x[] and WF[] are 1d)



void gnuprint(FILE *gp, double x[], int N)

{

int i;

fprintf(gp, "plot '-' with lines\n");

for (i=0; i<N; i++){fprintf(gp, "%g %g\n", x[i],WF[2*i+1]);

}




fflush(gp);
fprintf(gp, "e\n");


}


What I really want to do next is plot the imaginary points on the same plot which are next to the real in the array: x[i], WF[2*i+2]


If I simply just add a



fprintf(gp, "%g %g\n", x[i],WF[2*i+2]); //The imaginary values


into the loop, when 'with lines' specified, the two plots link together (plot points join up). Using dots solves this but I would like both plots to be separately linked with lines and hopefully different colours. Can someone help?


This is the form of the plot i'd like:


http://ift.tt/1FXlHCH


Editing ASM result of an operation in C when compilling in GCC

me and my friend got a computer architecture project and we don't really know how to get to it. I hope you could at least point us in the right direction so we know what to look for. As our proffesor isn't really good at explaining what we really need to do and the subject is rather vague we'll start from the beginning.


Our task is to somehow "edit" GCC to treat some operations differently. For example when you add two char arguments in a .c program it uses addb. We need to change it to f.e. 16bit registers(addl), without using unnecessary parameters during compilation(just regular gcc p.c -o p). Why or will it work doesn't really matter at this point. We'd like to know how we could change something inside GCC, where we can even start looking as I can't find any information about similar tasks besides making plugins/extensions. Is there anything we could read about something like this or anything we could use?


Poker Program in c Programming

I've put together a program that deals out a hand poker perfectly. Now I want the program to realize when the hand that is dealt is straight, flush, pair, 3 of a kind, and 4 of kind. The program runs but never prints the right condition when needed to, I believe I have some placement or logic error that I can't find. Here's what I have so far.



#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define SUITS 4
#define FACES 13
#define CARDS 52
#define HAND 5//draw only 5
#define TRUE 1//positive print condition
#define FALSE 0//negative print condition

//prototypes
shuffle( unsigned int wDeck[][FACES]);//shuffling modifies wDeck
deal(unsigned int wDeck[][FACES], const char *wFace[],
const char *wSuit[] );//dealing doesn't modify the arrays


//true/false conditions
typedef int bool;
bool straight, flush, four, three;
int pairs; //0,1, or 2



int main()
{
//initialize suit array
const char *suit[ SUITS ] =
{
"Hearts", "Diamonds", "Clubs", "Spades"
};

//initialize face array
const char *face[ FACES ] =
{
"Ace", "Deuce", "Three", "Four",
"Five", "Six", "Seven", "Eight",
"Nine", "Ten", "Jack", "Queen", "King"
};

int suitInHand[SUITS], facesInHand[FACES];

analyzeHand(suitInHand, facesInHand);

//initialize deck array
unsigned int deck[SUITS][FACES] = { 0 };

srand( time( NULL ) );//seed random-number generator

shuffle( deck );//shuffle the deck
deal( deck, face, suit );//deal the deck

}//end main

//shuffle cards in deck
shuffle( unsigned int wDeck[][FACES])
{
size_t row;//row number
size_t column;//column number
size_t card;//counter

//for each of the cards, choose slot of deck randomly
for( card = 1; card <= CARDS; ++card) {

//choose new random location until unoccupied slot found
do {
row = rand() % SUITS;
column = rand() % FACES;
}
while( wDeck[ row ][ column ] !=0);
//end do-while

//pace card number in chosen slot of deck
wDeck[ row ][ column ] = card;
}//end for
}//end function shuffle

//deal cards in deck
deal(unsigned int wDeck[][FACES], const char *wFace[],
const char *wSuit[] )
{
size_t card;//card counter
size_t row;//row counter
size_t column;//column counter

//deal each of the cards
for( card = 1; card <= HAND; ++card) {

//loop through rows of wDeck
for( row = 0; row < SUITS; ++row) {

//loop through column of wDeck for current row
for( column = 0; column < FACES; ++column) {

//if slot contains current card, display card
if( wDeck[ row ][ column ] == card ) {
printf("%5s of %-8s%c", wFace[ column ], wSuit[ row ],
card % 2 == 0 ? '\n' : '\t' );//2 column format
}//end if
}//end for
}//end for
}//end for
}//end function deal

analyzeHand(int suitsInHand[], int facesInHand[])
{
int num_consec = 0;
int rank, suit;

straight = FALSE;
flush = FALSE;
four = FALSE;
three = FALSE;
pairs = 0;

for (suit = 0; suit < SUITS; suit++)
if ( suitsInHand[suit] == 5)
flush = TRUE;

rank = 0;
while ( facesInHand[rank] == 0)
rank++;

for (; rank < FACES && facesInHand[rank]; rank++)
num_consec++;

if(num_consec == 5){
straight = TRUE;
return;
}

for(rank = 0; rank < FACES; rank++) {
if(facesInHand[rank] == 4)
four = TRUE;
if(facesInHand[rank] == 3)
three = TRUE;
if(facesInHand[rank] == 2)
pairs++;
}

if(four)
printf("Four of a kind\n");
else if(straight)
printf("Straight\n");
else if(pairs == 2)
printf("Two Pairs\n");
else if(pairs == 1)
printf("Pair\n");
else
printf("Better Luck Next Time\n");
}

: syntax error near unexpected token `('?

Can anyone tell where the problem is?



someone@someone:~/Desktop$ cat morning.c



#include <stdio.h>
int main (int argc, char** argv)
{
printf ("Good Morning") ;
return 0;
}



someone@someone:~/Desktop/9raya$ ./morning.c
./morning.c: line 2: syntax error near unexpected token `('
./morning.c: line 2: `int main (int argc, char** argv)'


I really don't see where the problem is.


c language scanf - fflush(stdin) - doesnt work

When I use scanf more than one time the program do not wait for another input. Instead it exits


I learned that I could put a blank space before the conversion specifier in the scanf-function - yes that solved the problem and I guess that has to do with the inputstream, that is - if its a newline character in the inputstream the scanf will consume it immediately.



scanf(" %f", &value);


But if its so - why could I not use the fflush(stdin) instead? I have tried but it doesnt work.



#include <stdio.h>
int main()
{

float value;
char ch;

printf("input value: ");
scanf("%f", &value);
fflush(stdin);
printf("input char: ");
scanf("%c", &ch);

return (0);
}

Run a program using cblas

I need to start a program with using cblas.h library. I download cblas.tgz and decompile it, I Run the command:



ln -s Makefile.LINUX Makefile.in


and try to run my program.


But I have this error.


I run my program used gcc main.c -cblas or gcc main.c, but the error is same.


I need to add a parameters in gcc compile?


Caching proxy cannot fully render page

I am building a caching proxy that should only process GET requests and store them in a cache. At the moment, I can see some packets printing but it gets stuck and cannot render the page. Also when I close the tab, a segfault occurs.



#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
#include <netdb.h>
#include <signal.h>

#include "cache.c"
#include "http.c"

cache_t *cache;
int cache_size/*in B*/, max_cache_size/*in B*/;

extern int accept4(int sock, struct sockaddr *client_addr, socklen_t *client_addr_len, int flags);
int send_data(int, char *);
int proxy(uint16_t);
int client(char *, char *, int, char *);
void *receive_func(void *);
int parse_request(char *, int);
int cache_check(char *, int);

int main(int argc, char ** argv)
{
if (argc != 3) {
printf("Error: input format should be: ./proxy <port number> <cache size in MB>\n");
return 1;
}
int port = atoi(argv[1]);
if (port < 1024 || port > 65535) {
printf("Invalid port number--must be between 1024 and 65535\n");
return 1;
}
max_cache_size = atoi(argv[2]) * 1000000;
if (max_cache_size < 0) {
printf("Invalid cache size entered\n");
return 1;
}
// Initialization of the cache
cache = (cache_t *)malloc(sizeof(cache_t));
cache->length = 0;
cache->next = NULL;
cache->URL = "";
cache->content = "";

cache_size = 0;
printf("port: %d\tcache size: %d B\n", port, max_cache_size);
signal(SIGPIPE, SIG_IGN);
return proxy(port);
}


/******************************************************

int send_data: sends message using a given port

******************************************************/
int send_data(int port, char *message) {
//must build http header before sending...

if (send(port, message, sizeof(message), 0) < 0) {
perror("Send error");
return 1;
}
return 0;
}


/******************************************************

int client: called if entry is not in cache

******************************************************/
int client(char *addr, char *message, int sock_proxy, char *URL) {
struct sockaddr_in server_addr;
char response[MAX_MSG_LENGTH];
memset(response, 0, MAX_MSG_LENGTH);

int sock;
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
perror("Create socket error:");
return 1;
}

printf("Socket created (client)\n");
server_addr.sin_addr.s_addr = inet_addr(addr);
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(80); //convention for Internet

if (connect(sock, (struct sockaddr*)&server_addr, sizeof(server_addr)) < 0) {
perror("Connect error");
return 1;
}

printf("Connected to server %s\n", addr);
printf("////////////////////////\n%s\n**********************\n", message);
if (send(sock, message, MAX_MSG_LENGTH, 0) < 0) {
perror("Send error");
return 1;
}

int readlen;
char *packet = (char *)malloc(MAX_MSG_LENGTH*3);
memset(packet, 0, MAX_MSG_LENGTH*3);
while ((readlen = recv(sock, response, sizeof(response),0))!= 0){
//printf("%s", response);
strcat(packet, response);
send(sock_proxy, response, readlen,0);
}

printf("%s\n", packet);
if(strstr(packet, "200 OK") != NULL){ //must be 200 response
while((cache_size+sizeof(packet)) > max_cache_size){
cache_t *temp = cache;
cache = cache->next;
cache_size -= temp->length;
free(temp);
}
printf("\n\n\nmax: %i current: %i\n\n\n", max_cache_size, (int)strlen(packet));
add_cache_entry(&cache, packet, URL);
cache_size += (int)strlen(packet);
}
return 0;

}

/******************************************************

int proxy: listens for connection requests

******************************************************/
int proxy(uint16_t port)
{
/* Create server socket*/
int sock, accepted_client;
unsigned int client_addr_len;
struct sockaddr_in socket_addr, client_addr;

if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
perror("Create socket error:");
return 1;
}

printf("Socket created (proxy)\n");

socket_addr.sin_addr.s_addr = htonl(INADDR_ANY); //should this be changed to localhost?
socket_addr.sin_family = AF_INET;
socket_addr.sin_port = htons(port);

/*Bind socket to an address*/
if (bind(sock, (struct sockaddr *) &socket_addr, sizeof(socket_addr)) < 0) {
perror("Bind error");
return 1;
}


printf("Listening for connections...\n");
/*Listen for connections */
listen(sock, 0);

while (1){
/* Accept the connection */
accepted_client = accept4(sock, (struct sockaddr *) &client_addr, &client_addr_len,0);
if (accepted_client < 0) {
perror("Accept error");
return 1;
}
printf("Accepted client: %i \n", accepted_client);

pthread_t tid;
int result;
if((result = pthread_create(&tid, NULL, (void *)receive_func, (void *)&accepted_client))){
perror("Creation of thread failed");
return 1;
}
}
return 0;
}

/******************************************************

void *receive_func: threads start in this function;
parse message

******************************************************/
void *receive_func(void *arg) {
int accepted_client = *(int *)arg;
char msg[MAX_MSG_LENGTH];
while(1) { //change this later
memset(msg, 0, MAX_MSG_LENGTH);
if (recv(accepted_client, msg, MAX_MSG_LENGTH, 0) < 0 ) {
perror("Recv error");
}
if(strstr(msg, "Connection: close")!=NULL) break;
if(msg[0] == 'G') {
printf("Received a GET request\n");
parse_request(msg, accepted_client);
}

}
pthread_exit(NULL);
return 0;
}

char *get_URL_from_request(char *request) {
char *copy = strdup(request);

void *temp = (void *)copy;
temp += 4 * sizeof(char); //get past "GET "
copy = (char *)temp;

int i;
for (i = 0; i < strlen(request); i++) {
if (copy[i] == ' ') {
char *URL = (char *)malloc(i * sizeof(char));
memcpy(URL, copy, i);
return URL;
}
}
return NULL;
}

char *get_host_from_request(char *request) {
char *host;
host = strtok(request,"//");
host = strtok(NULL,"/");
return host;
}

/******************************************************

int parse_request: deals with GET requests

******************************************************/
int parse_request(char *msg, int sock) {
printf(" *** INCOMING REQUEST ***\n");
char *msg_whole;
msg_whole = malloc(MAX_MSG_LENGTH);
strcpy(msg_whole, msg);
char *URL = get_URL_from_request(msg); //get target URL; will need for caching
char *host = get_host_from_request(msg); //get host
printf("FINAL URL: %s\nFINAL HOST: %s\n", URL, host);
char *ip_addr = host_to_ipaddr(host);
if(ip_addr == NULL) return 1;
if(cache_check(URL, sock)) return 0;
client(ip_addr, msg_whole, sock, URL);


free(URL);
return 0;
}

int cache_check(char *URL, int accepted_client){
cache_t *cache_entry;
if((cache_entry = search_cache(&cache, URL)) == NULL){
printf("Entry not i cache\n\n");
return 0;
} else {
printf("entry in cache\n\n");
enforce_LRU_middle(&cache, URL);
send_data(accepted_client, cache_entry->content);
return 1;
}
return 0;
}


Here is my cache.c





#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>

typedef struct cache {
struct cache *next;
unsigned int length;
char *URL;
char *content;
} cache_t;


#define MAX_MSG_LENGTH (1024*16)
#define MAX_BACK_LOG (5)
#define MAX_HOST_LENGTH (255)
#define IP_ADDR_LENGTH (32)

//add entry to end of cache, in accordance with LRU
int add_cache_entry(cache_t **, char *, char *);

//moves entry used in the middle to the end of the cache, has become most recently used
int enforce_LRU_middle(cache_t **, char *);

//removes first entry (LRU entry) in cache
int enforce_LRU_head();

//search cache by URL
cache_t *search_cache(cache_t **, char *);


int add_cache_entry(cache_t **cache, char *data, char *URL) {
//MUST CHECK AVAILABLE CACHE SPACE!
cache_t *head = *cache;
if(head->next==NULL){ //head
head->content = data;
head->URL = URL;
head->next = NULL;
head->length = (int) (sizeof(data));
printf("Saved: \nURL:%s\nPacket:%s\n", head->URL, head->content);
} else { // append last
cache_t *iterater = *cache;
while (iterater->next != NULL) {
iterater = iterater->next;
}
cache_t *newObj = (cache_t *)malloc(sizeof(cache_t));
newObj->content = data;
newObj->URL = URL;
newObj->next = NULL;
newObj->length = 0;
iterater->next = newObj;
printf("Saved: \nURL:%s\nPacket:%s\n", newObj->URL, newObj->content);
}

return 0;
}

int enforce_LRU_middle(cache_t **head, char *URL) {
cache_t *cache = *head;
cache_t *iterator = cache;
cache_t *prev = iterator;
cache_t *last = cache;
while (last->next != NULL) {
last = last->next;
}
while (iterator != NULL) {
if (strcmp(iterator->URL, URL) == 0) { //FOUND IT
if (iterator != last && cache -> next != NULL) {
//not last and of a cache of size > 1
prev->next = iterator->next;
last->next = iterator;
iterator->next = NULL;
return 0;
}
}
prev = iterator;
iterator = iterator->next;
}
return 1;
}

cache_t *search_cache(cache_t **cache, char *URL) {
cache_t *iterator = *cache;
while (iterator != NULL) {
if (strcmp(iterator->URL, URL) == 0) {
return iterator;
}
iterator = iterator->next;
}
return NULL;
}



gcc how to define 80bit size variable

I need to declare 80bit size variable in C program compiled by gcc (I need it to pass data to asm procedure which works on fpu, which is called by this program written in C) My architecture is AMD x64 I tried long double, __float80, but for them sizeof returns 12 insted of 10. So how to declare such variable?


thanks in advance


Eclipse and OpenOCD works only, if I program the mcu on discovery board

(sorry for my English I am not native English)


I'd like to program and debug an STM32F030 MCU with Eclipse, OpenOCD and ST-link. I have an STM32F4 Discovery board that includes an ST-link debugger.


My problem is: Programming the STM32F4 MCU on the discovery board works very well. I use Eclipse, OpenOCD and the ST-link (ST-link is actually on the board). With this configuration of the IDE I believe I should be able to program other stm microcontrollers that are on a different PCBs. (Of course after I connected them eachother and turned off 2 jumpers)


I'd like to program an STM32F030 MCU. When I connect this MCU to the ST-link, "STM32 ST-link Utility" says that the connection is fine, so I guess, I should be able to program it. But when I try to program it, Eclipse always shows the same error message: "Quit (Expected signal SIGINT when the program is resumed) - Exception condition detected on fd 0 - error detected on stdin"


Probably the problem is with the settings of my IDE, but I have no idea what could it be. How is it possible, that I can program the mcu of the discovery board but I can't do the same thing with another mcu?


Do you have any idea?


Thank you for your help in advance!


how to pass an integer to a function and return a string

I am trying to write a function that passes an int as a parameter and returns a string which is generated from a mysql query. I would one I have that working like to be able to pass a number of parameters (1 int and 2 chars) and have returned 3 strings, I guess those will require a struct and pointers but i'll start with the simple stuff.. crawl first..run later :)


Here is the code I have written I have removed the function but it's failing on compile at the line



retString = strFunction(int Value);


with the error:



warning: assignment makes pointer from integer without a cast [enabled by default]


I can post the full code if required..


Many Thanks in advance.



int main(int argc, char *argv[])
{

char *retString;
retString = strFunction(int Value);
printf("The Return string is: %s", retString);
Exit (0);

}


char *strFunction(int value)
{

perform code here using value;
Return retString;

}

Creating Linked List of Locations in C

FIX: I wasn't saving the locations back into world so I was just leaking the information. Credit to Skeeto.



while(!feof(fp)){
loc = readLocation(fp);
join(loc,world);
}


should actually be



while(!feof(fp)){
loc = readLocation(fp);
world = join(loc,world);
}


EDIT: As mentioned in the comments, yes I am a student, but I'm not looking for someone to do my work for me. I'm simply trying to locate possible logic errors because if I could fill this list properly, I can finish my project very easily. This is just a small portion of a very immersive project, helping with this will only allow me to continue the project, not complete it and turn it in. I only provided so much detail because 1) I've never posted here before so didn't know any better, and 2) wanted the reader to understand the workings of this in order to aid them in assisting me. Also, with any concerns as to skype, if that ended up being where successful help was given, I would provide the fix above this 'edit' as well as crediting the stackoverflow user for helping.


TLDR: Yes I'm a student, No im not trying to have someone do my project. This is a very small portion and will only allow me to continue, not complete. If help was given via skype I would update this post with the fix as well as credit the helper.


Hello and thank you for any help in advance.


I am trying to create a linked list that holds objects of type Location *. I have Location defined as



typedef struct location{
char *name;
char *longer;
char *shorter;
char *north;
char *south;
char *east;
char *west;
char *logic;
int visited;
char *items[20];
} Location;


Furthermore I can succesfully read in all the values for the location and display all attributes so that is not an issue.


In the 'engine' of my game (the main), i attempt to read all the locations into a list as seen in the following (I'm certain readLocation works correctly because I threw a print statement into the loop printing the name of the locations using the loc variable)



world = 0;
FILE *fp = fopen("world.in","r");
char *garb = readToken(fp);
free(garb); //garbage token at begging of world.in just to check file exists
int count = 0; //used later, ignore for now
while(!feof(fp)){
loc = readLocation(fp);
join(loc,world);
}


world is global variable declared as Node * and initialized to 0 (I think i need to do that but am not sure)


In olist.h I create the node structure as



typedef struct node
{
Location *place;
struct node *next;
} Node;


and in olist.c this is how i construct the Node as well as join the nodes



//place is the attribute of the Node that holds the location and next points to the next Node in the list
Node *newNode(Location *loc,Node *next)
{
Node *n = malloc(sizeof(Node));
if (n == 0)
{
fprintf(stderr,"newNode: out of memory!\n");
exit(1);
}
n->place = loc;
n->next = next;
return n;
}

//s is the location i wish to join to the list and rest is list I'm joining to
Node *join(void *s,Node *rest)
{
return newNode(s,rest);
}


Unfortunately, after successfully reading in all locations, world is still an empty list. Thanks for any help and I will be happy to provide further information via this forum or skype: F3V3Rz_MoDz (its a very old name)


What differences in c/c++ language in arm and x86 architectures [closed]

I'm trying to port code originally written for x86 architecture to arm.


http://ift.tt/1EgkETz


Originally it was developed for msvc/win32 and has many bugs in code, so there may be UB.


Code is working on x86 when compiled with gcc, but on arm it has different behaviour. It seems to lose some data in arrays and weapon switch does not work. It affected both server and client libraries.


Application is single-threaded, so it is not synchronization problem.


Char is unsigned by default on arm, so i add -fsigned-char to compiler flags, but it didn't solved the problem. What other differences is there between arm and x86 c code?


I tried to compile code on arm with gcc and clang and there is no differences, so it is not a compiler bug.


P.S I compiled code for x86 with gcc-4.9 (instead of 4.8) and got same behaviour. After that i combined two compilers and found that problem was in net_encode.c.


By the time, sebastien chevalier found that


iValue /= pField->multiplier; iValue *= pField->multiplier;


when iValue is integer and pField->multiplier==1.0f sometimes changes integer values.


It can be fixed by adding check if pField->multiplier != 1.0f before multiply.


add element to a linked list(C)

I want to make a link list that i can add more element to later but the problem i have with the current code is that the all previous elements are overwritten by the last element added.here is my code:



#include<stdio.h>
#include<stdlib.h>
#include<string.h>

struct node
{
char *name;
struct node *next;
}*head;



void add( char *str )
{
struct node *temp;
temp=(struct node *)malloc(sizeof(struct node));
temp->name=str;
if (head== NULL)
{
head=temp;
head->next=NULL;
}
else
{
temp->next=head;
head=temp;
}
}

void display(struct node *r)
{
r=head;
if(r==NULL)
{
return;
}
while(r!=NULL)
{
printf("%s ",r->name);
r=r->next;
}
printf("\n");
}

int main()
{
char *str;
struct node *n;
head=NULL;
while(scanf("%s",str) == 1)
{
add(str);
display(n);
}
return 0;
}

moved from cygwin to VisualStudio2013, error LNK2019, snprintf(), c

I'm trying to run a unix compiler-project written in c with MS Visual-Studio 2013 and I can't get rid of the following error:



error LNK2019: unresolved external symbol "_snprintf" referenced in
function "PUBLIC void SyntaxError( int Expected, TOKEN CurrentToken )"


If I get it right it is a problem where VisualStudio can't find the body/declaration from the snprintf() function, which should be defined in stdio.h.


The project works fine with cygwin. I had to add _CRT_SECURE_NO_WARNINGS to preprocessor settings to get this far, but i don't think that has a influence.


Here is the named function:



#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "line.h"
#include "strtab.h"
#include "scanner.h"

[..code..]


PUBLIC void SyntaxError( int Expected, TOKEN CurrentToken )
{
char s[M_LINE_WIDTH+2];

snprintf( s, sizeof(s), "Syntax: Expected %s, got %s\n", Tokens[Expected], Tokens[CurrentToken.code] );
Error( s, CurrentToken.pos );
}


If you can help me or there is anything else you need to know please tell me. It's my 3rd day now and I am running out of ideas ;).


So far... Tobias


How can i see the output of the Visual Studio if i have to terminate the console?

I have to count the digits, white spaces and other characters in C using Visual Studio 2013. So, i input something and then i have to recive the output. The problem is that i don't know how to exit the 'inputting' mode. All i can do is input text from keyboard or close the console.


Notes:



  • I am using Console Application, i've tried Windows Application but no luck

  • I've tried with and without Debug.

  • In Eclipse this exact code is working


Eclipse example:


He has 10 apples


digits = 1 1 0 0 0 0 0 0 0 0 , white space = 4, other= 11



main(){

int c, i, nwhite, nother;
int ndigit[10];

nwhite = nother = 0;

for (i = 0; i < 10; ++i)
ndigit[i] = 0;

while ((c = getchar()) != EOF)
if (c >= '0' && c <= '9')
++ndigit[c - '0'];
else if (c == ' ' || c == '\n' || c == '\t')
++nwhite;
else
++nother;

printf("digits = ");
for (i = 0; i < 10; i++)
printf("%d ", ndigit[i]);

printf(", white space = %d, other= %d", nwhite, nother);
getchar();
return 0;
}

Printf in C (types)

I just started programming in C. And I don't really understand the following code:


printf("%zu",i) ; or instead of %zu what are the other things that I can write(I know that they depend on the type of i) and which one is for what?


Thanks.


Understanding GCC inline assembly with a Hello World program

A friend helped me come up with the following code to use inline assembly in GCC on a 64-bit Windows machine:



int main() {
char* str = "Hello World";
int ret;

asm volatile(
"call puts"
: "=a" (ret), "+c" (str)
:
: "rdx", "rdi", "rsi", "r8", "r9", "r10", "r11");

return 0;
}


After compiling with -S -masm=intel (I prefer Intel syntax), I get this assembly code:



.file "hello.c"
.intel_syntax noprefix
.def __main; .scl 2; .type 32; .endef
.section .rdata,"dr"
.LC0:
.ascii "Hello World\0"
.text
.globl main
.def main; .scl 2; .type 32; .endef
.seh_proc main
main:
push rbp
.seh_pushreg rbp
push rdi
.seh_pushreg rdi
push rsi
.seh_pushreg rsi
mov rbp, rsp
.seh_setframe rbp, 0
sub rsp, 48
.seh_stackalloc 48
.seh_endprologue
call __main
lea rax, .LC0[rip]
mov QWORD PTR -8[rbp], rax
mov rax, QWORD PTR -8[rbp]
mov rcx, rax
/APP
# 7 "hello.c" 1
call puts
# 0 "" 2
/NO_APP
mov DWORD PTR -12[rbp], eax
mov QWORD PTR -8[rbp], rcx
mov eax, 0
add rsp, 48
pop rsi
pop rdi
pop rbp
ret
.seh_endproc
.ident "GCC: (x86_64-posix-seh-rev1, Built by MinGW-W64 project) 4.9.2"


It works, but it sure looks messy with what appears to be superfluous code. Then again, my last experience with assembly was with the 65816 back in the 80s, and it wasn't inline. Anyway, I cleaned up the code, and the following accomplishes the exact same thing, as far as I can tell:



.intel_syntax noprefix
.data:
.ascii "Hello World\0"
.text
.globl main
main:
sub rsp, 48
lea rax, .data[rip]
mov rcx, rax
call puts
mov eax, 0
add rsp, 48
ret


Much simpler. What's all that extra stuff GCC added?


Why isnt my 2d array being allocated at all processes on my university cluster?

I am running multiplication matrix code on my cluster and i am certain it works just fine. i even used the Scatterv and it scatters flawlessly... but i dynamically allocated my result matrix on every Process with size sendcount[world_rank] rows and z columns, i checked and these numbers are correct to the dot... only one Process allocated the array and the rest just prints an address or something.


My code does the matrix multiplication here:



count = 0;
while(count < z){

for (i = 0; i < sendcount[world_rank]; i++){

for(j = 0; j < y; j++){
//printf("matrix1[%d][%d] * matrix2[%d][%d] = ", i, j, j, count);
resultmatrix[i][count] += matrix1[i][j] * matrix2[j][count];
//printf("%d ", resultmatrix[i][count]);

}
//printf("rank: %d, i: %d count: %d resultmatrix: %d\n", world_rank, i, count, resultmatrix[i][count]);

}
count++;
//printf("\n");
}


When i go to print the resultmatrix at each process for testing, only my root process prints actual values... could this be a problem from my cluster or am i missing something?


Single processes tree with exec

I have to write a script creating processes tree using fork() function. Then I need to use the exec() function inside the script, to generate only ONE processes tree, with pstree -c command.


Ok, so I created processes tree, that's not a problem, let's say:



int main() {
int pid1, pid2;
if(pid1 = fork()) {
printf("%d", pid1);
} else if (pid2 = fork()) {
printf("%d", pid2);
} else {
printf("%s", "parent process");
}
return 0;
}


But how do I use exec function to invoke pstree -c command? And how can I show only one specific tree?



execl("/bin/pstree -c", "pstree -c", 0, 0);


I tried with /bin/, without it...nothing works, the tree is not displayed when I run the script.


And it would display the whole tree anyways, not just the forks I used.


How can I do that?


Inconstant difference in address of Struct when adding

I'm working on a memory where I use this header in allocated blocks. I was trying out pointer arithmetic to return new regions. Here's a simple question. When I add 1,2,3 to an address of integer, the compiler brings the next first,second,third integer's address, and they all vary by sizeof(int). But in this code a struct is of size 8. And the address vary alternatively by 2 and 8. Heres a code, with the output i get:



#include <stdio.h>
#include <stdlib.h>

typedef struct header {
int size;
int magic;
}header;

int main() {

int n = 10;
printf("size of int %d\n", sizeof(n));
printf("addr %p\n", &n);
printf("addr+1 %p\n", &n+1);
printf("addr+2 %p\n", &n+2);
printf("addr+3 %p\n", &n+3);

header *h = malloc(sizeof(header));
printf("size of header %d\n", sizeof(header));
printf("addr %p\n", h);
printf("addr+1 %p\n", h+1);
printf("addr+2 %p\n", h+2);
printf("addr+3 %p\n", h+3);


return 0;
}


OUTPUT



size of int 4
addr 0xbfeb7898
addr+1 0xbfeb789c
addr+2 0xbfeb78a0
addr+3 0xbfeb78a4

size of header 8
addr 0x8706008
addr+1 0x8706010
addr+2 0x8706018
addr+3 0x8706020

How to merge source files into one

I have a projet who have a lot of (headers and c files). I want merge code into one file.


It's possible ussing gcc or another tool?



gcc [...] -E [...]


It's give not good result


How reach it?


Problems programming RAID System

I'm working on my final assignment for my class programming with c but I'm not getting it working.


This is my assignment:


Some computers contain a so called RAID system. This system, in essence, uses multiple places to store data. Create a program that will do just that. The input of the program should be a text file. The output should be two separate files containing every other character from the original file. Also give the possibility of entering two split files and merge them to the original file. So after running the program: The original file contains the text : ”Dutch people are tall.”. Split file 1 contains: ”Dthpol r al” Split file 2 contains: ”uc epeaetl.” Now if split file 1 would be saved on USB stick 1, and split file two would be saved on USB stick 2, you’d need half the time for saving the file! 3


This is the code I got so far but it keeps crashing. Hope you guys are able to help me.



#include <stdio.h>
#include <stdlib.h>

int main()
{
char cUsb1;
char cUsb2;
int n;
char str[128];

FILE *ptr_readfile;
FILE *ptr_sizeoffile;
FILE *ptr_usb1;
FILE *ptr_usb2;

ptr_readfile = fopen("Dutch People.txt","r");

ptr_sizeoffile = fopen("Dutch People.txt", "r");

n = sizeof(ptr_sizeoffile);
printf("%i\n", n);

while(ptr_readfile != NULL)
{
if (ptr_readfile != EOF)
{
cUsb1 = fgetc(ptr_readfile);
printf("%c\n", cUsb1);
ptr_usb1 = fopen("USB1.txt", "w");
fwrite(cUsb1 , n , n , ptr_usb1);
if(!ptr_usb1)
{
return 1;
}

cUsb2 = fgetc(ptr_readfile);
printf("%c\n", cUsb2);
ptr_usb2 = fopen("USB2.txt", "w");
fwrite(cUsb2 , n , n , ptr_usb2);
if(!ptr_usb2)
{
return 1;
}
}
break;

}

fclose(ptr_readfile);
fclose(ptr_usb1);
fclose(ptr_usb2);

return 0;
}

Dividing Algorithm in C till 0.005

How to make this in C


321/123\2.6097....


321 246 (2x123)




075 073.8 (6x123)/10




001.2 001.107 (9*123)/1000




000.0930 000.0861 (7*123)/10000


Asynchronous C client for a multiclient C server

I have a client which is working fine, but whenever I run a new client, sometimes I don't receive the sent message on the other client already running, while using telnet it works flawlessly, the message "broadcasts" to all connected clients, and I want whenever a message is received to one of the clients to show even if I didn't already send a message. Should I use select on clients ? and what should be changed ?


client.c:



#include <stdio.h> //printf
#include <string.h> //strlen
#include <sys/socket.h> //socket
#include <arpa/inet.h> //inet_addr
#include <unistd.h>

int main(int argc , char *argv[]){
int sock;
struct sockaddr_in server;
char message[256] , server_reply[256];

//Create socket
sock = socket(AF_INET , SOCK_STREAM , 0);
if (sock == -1)
{
printf("Could not create socket");
}
puts("Socket created");

server.sin_addr.s_addr = inet_addr("127.0.0.1");
server.sin_family = AF_INET;
server.sin_port = htons( 9034 );

//Connect to remote server
if (connect(sock , (struct sockaddr *)&server , sizeof(server)) < 0){
perror("connect failed. Error");
return 1;
}

puts("Connected\n");

//keep communicating with server
for(;;){

printf("Enter message: ");
memset(message, 0, 256);
fgets(message, 256,stdin);
// scanf("%s" , message);

//Send some data
if( send(sock , message , strlen(message) , 0) < 0)
{
puts("Send failed");
return 1;
}

//Receive a reply from the server
if( recv(sock , server_reply , 256 , 0) < 0)
{
puts("recv failed");
break;
}

printf("Server Reply: %s\n", server_reply);
server_reply[0]='\0';
}

close(sock);
return 0;
}


server.c:



/*
** selectserver.c -- a cheezy multiperson chat server
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>

#define PORT "9034" // port we're listening on

// get sockaddr, IPv4 or IPv6:
void *get_in_addr(struct sockaddr *sa)
{
if (sa->sa_family == AF_INET) {
return &(((struct sockaddr_in*)sa)->sin_addr);
}

return &(((struct sockaddr_in6*)sa)->sin6_addr);
}

int main(void){
fd_set master; // master file descriptor list
fd_set read_fds; // temp file descriptor list for select()
int fdmax; // maximum file descriptor number

int listener; // listening socket descriptor
int newfd; // newly accept()ed socket descriptor
struct sockaddr_storage remoteaddr; // client address
socklen_t addrlen;

char buf[256]; // buffer for client data
int nbytes;

char remoteIP[INET6_ADDRSTRLEN];

int yes=1; // for setsockopt() SO_REUSEADDR, below
int i, j, rv;

struct addrinfo hints, *ai, *p;

FD_ZERO(&master); // clear the master and temp sets
FD_ZERO(&read_fds);

// get us a socket and bind it
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;
if ((rv = getaddrinfo(NULL, PORT, &hints, &ai)) != 0) {
fprintf(stderr, "selectserver: %s\n", gai_strerror(rv));
exit(1);
}

for(p = ai; p != NULL; p = p->ai_next) {
listener = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
if (listener < 0) {
continue;
}

// lose the pesky "address already in use" error message
setsockopt(listener, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int));

if (bind(listener, p->ai_addr, p->ai_addrlen) < 0) {
close(listener);
continue;
}

break;
}

// if we got here, it means we didn't get bound
if (p == NULL) {
fprintf(stderr, "selectserver: failed to bind\n");
exit(2);
}

freeaddrinfo(ai); // all done with this

// listen
if (listen(listener, 10) == -1) {
perror("listen");
exit(3);
}

// add the listener to the master set
FD_SET(listener, &master);

// keep track of the biggest file descriptor
fdmax = listener; // so far, it's this one

// main loop
for(;;) {
read_fds = master; // copy it
if (select(fdmax+1, &read_fds, NULL, NULL, NULL) == -1) {
perror("select");
exit(4);
}

// run through the existing connections looking for data to read
for(i = 0; i <= fdmax; i++) {
if (FD_ISSET(i, &read_fds)) { // we got one!!
if (i == listener) {
// handle new connections
addrlen = sizeof remoteaddr;
newfd = accept(listener,
(struct sockaddr *)&remoteaddr,
&addrlen);

if (newfd == -1) {
perror("accept");
} else {
FD_SET(newfd, &master); // add to master set
if (newfd > fdmax) { // keep track of the max
fdmax = newfd;
}
printf("selectserver: new connection from %s on "
"socket %d\n",
inet_ntop(remoteaddr.ss_family,
get_in_addr((struct sockaddr*)&remoteaddr),
remoteIP, INET6_ADDRSTRLEN),
newfd);
}
} else {
// handle data from a client
memset(buf, 0, 256);
if ((nbytes = recv(i, buf, sizeof buf, 0)) <= 0) {
// got error or connection closed by client
if (nbytes == 0) {
// connection closed
printf("selectserver: socket %d hung up\n", i);
} else {
perror("recv");
}
close(i); // bye!
FD_CLR(i, &master); // remove from master set
} else {
// we got some data from a client
for(j = 0; j <= fdmax; j++) {
// send to everyone!
if (FD_ISSET(j, &master)) {
// except the listener and ourselves
if (j != listener && j != i) {
if (send(j, buf, nbytes, 0) == -1) {
perror("send");
}
}
}
}
}
} // END handle data from client
} // END got new incoming connection
} // END looping through file descriptors
} // END for(;;)--and you thought it would never end!

return 0;
}

How can write this function in c programming?


typedef struct { int x; int y; } Point_t;
typedef struct { Point_t left_up; int right down; } Rectangle_t;


I have this function:



double maxSumConstPoint(double table[][COL_COUNT], int nRow, int leftUpY, int leftUpX, int* rightDownY, int* rightDownX){
int rDX; /*x coordinate of the right down corner of the rec*/
int rDY; /*y coordinate of the right down corner of the rec*/
double temp;
/*initialize the rectangular with the one including only one point*/
double sum=table[leftUpX][leftUpY];
*rightDownY=leftUpY;
*rightDownX=leftUpX;

/*Try all feasible rectangulars by changing the right down corner*/
for(rDY=leftUpY; rDY<nRow; ++rDY){
for(rDX=leftUpX; rDX<COL_COUNT; ++rDX){
temp=getSum(table, leftUpY, leftUpX, rDY, rDX);
if(temp>sum){
/*a better rectangular is found, perform an update */
sum=temp;
*rightDownY=rDY;
*rightDownX=rDX;
}
}
}

return sum;

}


I need to turn the following functions:



Rectangle_t maxSumConstPoint(double table[][COL_COUNT], int nRow, Point_t
left_up)


How can write this function?


bubbleSort doesnt work when printf(" "); removed from code

I am trying to make a dbms using unix file system ... In the code ... when I remove line 102 my bubbleSort doesnt work properly ... How does a printf statement affect immediately next statement?



#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct update_list {
int attribute_number; //give it in ascending order
char *value;
struct update_list *next;
};

void swap(struct update_list *a, struct update_list *b){
int temp = a->attribute_number;
char *temp_value;
temp_value = malloc(strlen(a->value)+1);
strcpy(temp_value,a->value);
a->attribute_number = b->attribute_number;
strcpy(a->value,b->value);
b->attribute_number = temp;
strcpy(b->value,temp_value);
}

void bubbleSort(struct update_list *start){
int swapped, i;
struct update_list *ptr1;
struct update_list *lptr = NULL;

/* Checking for empty list */
if (ptr1 == NULL)
return;

do
{
swapped = 0;
ptr1 = start;

while (ptr1->next != lptr)
{
if (ptr1->attribute_number > ptr1->next->attribute_number)
{
swap(ptr1, ptr1->next);
swapped = 1;
}
ptr1 = ptr1->next;
}
lptr = ptr1;
}
while (swapped);
}



int number_of_attributes(char* db_name, char* r_name)
{
FILE *fp;
char buff[50], fname[50];
int count = 0;
strcpy(fname,"_r");
strcat(fname,r_name);

char catalog_address[100];
strcpy(catalog_address, db_name );
strcat(catalog_address,"/_catalog_");
fp = fopen( catalog_address, "r" );
if (1)
//fscanf(fp, "%s", buff);
while (!feof(fp))
{
fscanf(fp, "%s", buff);
if (strcmp ( buff, fname)==0)
{
fscanf(fp, "%s", buff);
while((strcmp(buff,"__")!=0) && !feof(fp))
{
count++;
fscanf(fp, "%s", buff);
if (!feof(fp)) fscanf(fp, "%s", buff);

}
return (count);
}
/*while(strcmp(buff,"_")!=0)
fscanf(fp, "%s", buff);*/
//fscanf(fp, "%s", buff);
}
return (-1);
fclose(fp);
}

void print_list(struct update_list *start)
{
struct update_list *temp = start;
printf("\n");
while (temp!=NULL)
{
printf("%d ", temp->attribute_number);
temp = temp->next;
}
}
int insert(char* db_name, char* rel_name, struct update_list *attribute_values ){
FILE *catalog, *relation;
int i;
printf(" "); //problem here ...I cannot remove this
bubbleSort(attribute_values);
print_list(attribute_values);
char rel_address[100];

strcpy(rel_address, db_name );
strcat(rel_address,"/");
strcat(rel_address,rel_name);
relation = fopen(rel_address, "r");

//take the first element of att_list

char *PK;
PK = malloc(strlen(attribute_values->value)+1);
strcpy(PK,attribute_values->value);
strcat(PK,"\n");

//get num_of_attr = t
int t = number_of_attributes(db_name,rel_name);
//after every t lines, check value = value of first element
const size_t line_size = 300;
char* line = malloc(line_size);
int count = 0;
while (fgets(line, line_size, relation) != NULL){
if(count%t == 0){
if(strcmp(line, PK) == 0){
free(PK);
return -2;
}
}
count++;
}
free(line);
//else append at the end: each value of attr_list
struct update_list *current;
current = attribute_values;
char shellscript[10000];
strcpy(shellscript,"\n");
while(current != NULL){
strcat(shellscript,"echo ");
strcat(shellscript,current->value);
strcat(shellscript,">> ");
strcat(shellscript,rel_address);

strcat(shellscript,"\n");

current = current->next;
}

system(shellscript);
free(PK);

return 0;

}
int main(int argc, char* argv[]){

int i;
struct update_list *head,*current;

head = (struct update_list*)malloc(sizeof(struct update_list));
current = (struct update_list*)malloc(sizeof(struct update_list));

head->attribute_number = 3;
head->value = malloc(100);
strcpy(head->value, "kruthi");

head->next = current;

current->attribute_number = 2;
current->value = malloc(100);
strcpy(current->value,"kakjd");
current->next=NULL;

//bubbleSort(head);
insert(argv[1], argv[2], head);
free(head->value);
free(current->value);
free(head);
free(current);

return 0;
}


bubbleSort was working perfectly fine when kept in main function ...


Edit: I have called bubbleSort inside insert function, since stackoverflow doesnt give line numbers, I have put comment //the problem here to locate the printf statement.


Does GTK+ have runtime dependency

I am trying to follow the GTK+ hello world tutorial here. I compiled the code to executable and tried to run it. Then i got an error which said failed to load a particular package. I installed the package and ran the executable. Now, the executable ran perfectly as expected. Does this mean GTK+ has runtime dependencies on these modules?


So, should the system in which my executable runs have GTK+ installed ?


Can't my executable be a standalone program?


worst-case time complexity of str.find in python

The question is already in the title, what is the worst-case time complexity of the C implementation of str.find(string, substring) in Python if n is the length of string and m is the length of substring? The source code (http://ift.tt/1baWVqr) seems to talk about the boyer-moore-horspool algorithm, which according to Wikipedia has a worst-case complexity of O(m*n).


Call back programming w.r.t 'c' only, why we should use?

The point being saying w.r.t c only, as I am more comfortable in C.


I am not expecting a example which says this is how it works ... What I am expecting is why should we use the Call back function or some say it as function pointer.


I followed many blog and stack-overflow also, but not satisfied with any of those answers.


Let's say ( I am suggesting one scenario here, like sorting thing) we should use the call back thing, where a method/function will take more time for processing.


Let's say a process is there with one thread only, and the program is doing a sorting, which will take huge time ( let's assume > 1 min ). According to huge no of bloggers here we should use the function pointer. But how it would be useful ?


Any how we are having only one Program Counter and we will get some amount of time to process this process from CPU, then how it would be useful ?


If you think some other example is there to explain the function pointer concept please provide the example.


I saw some body suggesting like, if you will use function pointer, then the result u can collect later, but this sounds really awkward ! how is this even if possible ? How can u collect something from a function after returning from there ? the function would have been destroyed right !!!


In real time people use this for any change in events, so that they can get notification...( just adding a point )


I have seen some good programmer using this function pointer, I am dying to know why would I use this , surely there is something I am missing here...


Please reply, thanks in Advance.


Accessing attributes of structures stored in linked lists

Hello stackoverflow and thank you in advance for the help!


As the title says, I'm trying to find a specific location in a linked list and then be able to access its attributes. I know how to sort through the linked list but I can not figure out how to access the name attribute of the Locations.


I define my Location * structure as (These locations are stored into the list later):



#ifndef NESW_STRUCT
#define NESW_STRUCT
typedef struct location{
char *name;
char *longer;
char *shorter;
char *tip;
char *north;
char *south;
char *east;
char *west;
char *logic;
int visited;
char *items[20];
} Location;
#endif


My instructor provides us with a module to create a linked list as well as various functions to manipulate the list. The linked list is comprised of Node * which I believe hold the Locations as well as point to the next node in the list.



typedef struct node
{
Location *loc;
struct node *next;
} Node;


So in my game loop I create a global variable 'world' that is my linked list of (I think) Locations:



Node *world;


and



extern Node* world;


In other modules that also access it.


I then run a simple while loop in my main that creates a Location structure and then joins it to the Linked list(excluded from this post), world, using join(location,world) with the following functions my instructor provided, modified by me to work with Locations rather than void objects. I don't initialize world to anything before joining the first location to it, I think I may need to, but since its a core dump and crashes either way, I can't tell if it makes a difference/is necessary:



Node *
newNode(Location *place,Node *next)
{
Node *n = malloc(sizeof(Node));
if (n == 0)
{
fprintf(stderr,"newNode: out of memory!\n");
exit(1);
}
n->loc = place;
n->next = next;
return n;
}

Node *
join(Location *s,Node *rest)
{
return newNode(s,rest);
}


This all works perfectly fine so far and I create my list successfully. However, elsewhere in my program I created a function that maps through the world list and find the location that has a matching name to whichever name I pass to the function, which, logically, works correctly . I created a temp list that is equal to 'world', and then compared the name attribute of the head of the list to the name of the location I was looking for using, strcmp, returning that location if it matches, and setting the list = to the tail of the list if it doesn't.


Head and Tail are defined here, again provided in the module from my instructor:



Location *
head(Node *items)
{
return items->loc;
}

Node *
tail(Node *items)
{
return items->next;
}


If I understand these functions correctly, using head(list) should return a Location right, not a pointer? Then I should be able to just use 'location->name' to access the name? Apparently not though...


To save time of running through all the game logic just get to the part where it needs to compare the names, I tried writing some temporary code similar to how it would be in the mapping function, to test getting a location from the list and then accessing the attributes.


The probably wrong code I'm using to try and test accessing the list is:



Location *test = 0; //creating an empty location, (not sure if it needs to be initialized to 0 before assigning the desired value but I think I remember a mention of that during class)
test = head(world); //I would like to believe this sets test equal to the location of the head of the list world, but I am fairly certain this is where my error occurs because what is getting assigned to test really isn't a location
printf("%s",test->name); //basic print of the name attribute, I know this works logically because I use it elsewhere when dealing with locations not accessed through world, however this is what causes the core dump because I think I'm trying to access a garbage value so to speak


The program compiles with no errors and successfully reads all the the locations based on a debugging print statement I added. Any help, advice, or tips are greatly welcomed. I know people hate on kids that post here because they think they are trying to get their work done for free, but this is a very small part of an immersive project and once I figure this out, the game is essentially done other than content. I'm at a minor roadblock that is a major inhibitor and have tried everything my friend and I could think of and have even just started changing random data types in the Node struct and join/newNode functions as well as the Location struct hoping to either get lucky or figure out a solution through different error messages that occurred but as you can guess, no luck. Happy coding and your help is greatly appreciated.