Affichage des articles dont le libellé est Active questions tagged c - Stack Overflow. Afficher tous les articles
Affichage des articles dont le libellé est Active questions tagged c - Stack Overflow. Afficher tous les articles

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