#include <stdio.h>
#include <conio.h>
#include <graphics.h>
#include <stdlib.h>
typedef struct arr_col_1{
int x;
};
typedef struct arr_col_2{
int x, y;
};
typedef struct array{
int x1, y1;
};
void col_1(FILE *file, int row);
void col_2(FILE *file, int row);
int main(){
FILE* file;
int row = 0, col = 1, i;
char fname[40], chr;
int gd = DETECT, gm;
initgraph(&gd, &gm, "C:\\TurboC3\\BGI");
do{
printf("\nEnter the file which you want to vizualize = ");
scanf("%s", &fname);
file = fopen(fname, "r");
if(file == NULL){
printf("\nPlease Enter correct file name ");
}
}while(file == NULL);
chr = getc(file);
while(chr != EOF){
if(chr == '\n'){
row++;
}
if((row == 0)&&(chr == ',')){
col++;
}
chr = getc(file);
}
printf("%d row %d col", row, col);
if(col == 1){
col_1(file, row);
}
if(col == 2){
col_2(file, row);
}
getch();
return 0;
}
void col_1(FILE *file, int row){
struct arr_col_1 *arr1;
int i;
arr1 = (struct arr_col_1*)malloc(row * sizeof(struct arr_col_1));
for(i = 0; i < row; i++){
fscanf(file, "%d", &arr1[i].x);
printf("%d\n", arr1[i].x);
}
getch();
}
void col_2(FILE *file, int row){
struct arr_col_2 *arr2;
int i;
arr2 = (struct arr_col_2*)malloc(row * sizeof(struct arr_col_2));
for(i = 0; i < row; i++){
fscanf(file, "%d %d", &arr2[i].x, &arr2[i].y);
printf("%d %d\n", arr2[i].x, arr2[i].y);
}
getch();
}
the above code able to tell no of rows and col but it not show the data it is not able to read the data. please help me out in the above code i send file to the function but it look like i am not able to read the data. i dont know where the problem occurs please help. somewhere i think the problem lies between file pointer but code is run with no error
Related
How to delete an element from the array of type structure? Let's say if I register an item and then want to delete it how can I do that? The delete function is at the end of the code. I want to delete the item by giving the varunummer (id number). Any one know how to do it?
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define WORDLENGTH 30
#define MAX 5
struct varor {
int varunummer;
char namn[WORDLENGTH];
int lagersaldo;
};
int readLine(char s[], int length);
int ifVarunummerExist(int varunummer, const struct varor reg[], int nrOfGoods);
void registerVaror(struct varor reg[], int *nrOfGoods);
void getPrint(const struct varor reg[], int nrOfGoods);
void avregristreraVaror(struct varor reg[], int nrOfGoods);
int main(void) {
struct varor vRegister[WORDLENGTH];
int nrOfGoods = 0;
int run = 1;
while (run) {
char choice;
printf("\n\t\tMeny - Lager Program\n\n\
(1) Register\n\b\b\b\b\
(2) Print\n\
(3) Delete\n\
(4) Quit\n");
scanf(" %c%*c", &choice);
if (choice=='1')
registerVaror(vRegister, &nrOfGoods);
if (choice=='2')
getPrint(vRegister, nrOfGoods);
if (choice=='3')
avregristreraVaror(vRegister, nrOfGoods);
else if (choice=='4')
run = 0;
}
return 0;
}
int ifVarunummerExist(int varunummer, const struct varor reg[], int nrOfGoods) {
int i;
for (i = 0; i < nrOfGoods; i++)
if(reg[i].varunummer == varunummer)
return i;
return -1;
}
int readLine(char s[], int length) {
int ch, i=0;
while (isspace(ch=getchar()));
while (ch != '\n' && ch != EOF) {
if (i < length)
s[i++] = ch;
ch = getchar();
}
s[i] = '\0';
return i;
}
void registerVaror(struct varor reg[], int *nrOfGoods) {
char namn[WORDLENGTH], tmp[WORDLENGTH];
int varunummer, lagersaldo;
if (*nrOfGoods == MAX) {
printf("\nError! Finns inte plats kvar!\n");
return;
}
printf("Ange varunummer: ");
scanf("%d", &varunummer);
if (ifVarunummerExist(varunummer, reg, *nrOfGoods) >= 0) {
printf("\nVarunummer finns redan!\n");
return;
}
reg[*nrOfGoods].varunummer = varunummer;
printf("Ange namn: ");
readLine(reg[*nrOfGoods].namn, WORDLENGTH);
printf("Ange lagersaldo :");
scanf("%d", ®[*nrOfGoods].lagersaldo);
//reg[*nrOfGoods]=createVara(varunummer,namn,lagersaldo);
(*nrOfGoods)++;
}
void getPrint(const struct varor reg[], int nrOfGoods) {
int i;
printf("\nVarunummer \t Namn \t\t\t Lagersaldo\n");
for (i = 0; i < nrOfGoods; i++) {
printf(" %d \t\t %s \t\t\t %d\n",reg[i].varunummer,reg[i].namn,reg[i].lagersaldo);
}
}
void avregristreraVaror(struct varor reg[], int nrOfGoods) {
int run = 1;
while (run) {
char choice;
printf("\n (1) Delete \n (2) Exit");
scanf(" %c", &choice);
//DELETE IF CHOICE 1---------
if (choice == '1') {
int i, varunummer;
printf("Ange varunummer: ");
scanf("%d", &varunummer);
for (i = varunummer + 1; i < MAX; i++) {
reg[i - 1] = reg[i];
}
reg[i] = 0;
}
}
//QUIT TO MY MENU CHOICE 2--------
if (choice == '2')
run = 0;
}
You can try iterating through the array in a for loop UNTIL your varunummer is matched with the struct's property. Something along these lines (let's say you are searching for the member with varunummer = varunummerToLookFor), this shift all the elements in the array from the point onwards of your deletion by 1, hence, producing an array with the same sequence as before but with your wanted element removed. Hope that helps!
for(int i = 0, i < varorArraySize, i++){
if(varunummerToLookFor == varorArray[i].varunummer){
for (i = pos; i < varorArraySize - 1; i++)
{
varorArray[i] = varorArray[i + 1];
}
}
}
#include <stdio.h>
#include <stdlib.h>
#include "vettore.h"
int main(int argc, char *argv[]){
if(argc != 5)
printf("Incorrect parameters number\n");
else{
int n = atoi(argv[1]);
int *a = (int*) calloc(n, sizeof(int));
if(a == NULL)
printf("Unsufficient memory\n");
else{
finput_array(argv[2], a, n);
bubblesort(a, n);
foutput_array(argv[4], a, n);
int *oracle = (int*) calloc(n, sizeof(int));
finput_array(argv[3], oracle, n);
if(compare_array(a, oracle, n))
printf("PASS\n");
else
printf("FAIL\n");
}
}
}
I run the program this way: ./test_ordina_array.exe 12 TC4_input.txt TC4_oracle.txt TC4_output.txt but it gives me segmentation fault.
"TC4_output.txt" is created by the program while the other two files already exist.
This are the functions used:
void bubblesort(int a[], int n){
int i, j;
for(i = 0 ; i < n - 1; i++)
{
for(j = 0 ; j < n - i - 1; j++)
{
if (a[j] > a[j+1]) /* For decreasing order use < */
{
swap(&a[j], &a[j+1]);
}
}
}
}
void finput_array(char *file_name, int a[], int *n){
FILE *fd = fopen(file_name, "r");
if(fd == NULL)
printf("Errore in apertura del file %s\n", file_name);
else{
int i = 0;
fscanf(fd, "%d", &a[i]);
while(i<*n && !feof(fd)){
i++;
fscanf(fd, "%d", &a[i]);
}
fclose(fd);
if(i<*n)
*n = i;
}
}
void foutput_array(char *file_name, int a[], int n){
int i;
FILE *fd;
fd = fopen(file_name, "w");
if(fd == NULL)
printf("Errore in apertura del file %s\n", file_name);
else{
for(i=0; i<n; i++)
fprintf(fd, "%d\n", a[i]);
fclose(fd);
}
}
int compare_array(int a[], int b[], int n){
int i=0;
while(i<n && a[i] == b[i])
i++;
return (i==n) ? 1 : 0;
}
They are contained in "vettore.c" and "vettore.h" contains their prototypes.
The program has to order in ascending order the elements contained in the first txt file and write them in the output file.
You have problem when using finput_array
finput_array(argv[2], a, n);
Please replace by
finput_array(argv[2], a, &n);
this program create a file,write on the file, after read from that file, update data and then put the file's content into an array. When I run the code, it doesn't work right, in fact, all values printed except for Vet[i].squadra are zero. I debugged the code and I saw that AggiornaFile function resets to zero variable's values each time I use fseek and freed, so I think that fwrite update values into file with zeros.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define DIMMAX 4
#define DIMCAR 20
typedef char Stringa[DIMCAR];
typedef struct{
int vinte;
int perse;
int nulle;
} Partite;
typedef struct{
int subiti;
int effettuati;
} Goal;
typedef struct{
int squadra;
Partite partite;
Goal goal;
int punti;
} Nota;
typedef struct{
int squadra1;
int squadra2;
int goal1;
int goal2;
} Match;
void CreaFile(Stringa, int);
void DisputaMatch(Match *, int, int);
void AggiornaFile(Stringa, Match);
int CalcolaEsito(Match);
void DisputaFase(int, Stringa);
Nota CalcolaClassifica(Nota[], int, Stringa);
void ordina(Nota *, int);
void StampaClassifica(Nota[], int);
int calcolaNPartite(Nota);
void CreaFile(Stringa percorso, int valDati){
FILE *ptr;
Nota n;
int i;
ptr = fopen(percorso, "wb");
if(ptr ==NULL){
printf("File inesistente.\n");
}
else{
for(i=1; i<= valDati; i++){
n.partite.vinte = 0;
n.partite.perse = 0;
n.partite.nulle = 0;
n.goal.subiti = 0;
n.goal.effettuati = 0;
n.punti = 0;
n.squadra = i;
fwrite(&n, sizeof(Nota), 1, ptr);
}
fclose(ptr);
}
}
void DisputaMatch(Match *incontro, int S1, int S2){
int rand1,rand2;
incontro->squadra1 = S1;
incontro->squadra2 = S2;
rand1 = rand() % 5;
rand2 = rand() % 5;
incontro->goal1 = rand1;
incontro->goal2 = rand2;
}
void AggiornaFile(Stringa percorso, Match incontro){
FILE *ptr;
Nota n;
int esito;
ptr = fopen(percorso, "rb+");
if(ptr == NULL){
printf("File inesistente.\n");
}
else{
fseek(ptr, incontro.squadra1*sizeof(Nota), SEEK_SET);
fread(&n, sizeof(Nota), 1, ptr);
n.goal.effettuati += incontro.goal1;
n.goal.subiti += incontro.goal2;
esito = CalcolaEsito(incontro);
switch(esito){
case 0:
n.partite.nulle++;
n.punti += 1;
break;
case 1:
n.partite.vinte++;
n.punti += 3;
break;
case 2:
n.partite.perse++;
break;
}
fwrite(&n, sizeof(Nota),1, ptr);
fseek(ptr, incontro.squadra2*sizeof(Nota), SEEK_SET);
fread(&n, sizeof(Nota), 1, ptr);
n.goal.effettuati += incontro.goal2;
n.goal.subiti += incontro.goal1;
switch(esito){
case 0:
n.partite.nulle++;
n.punti += 1;
break;
case 1:
n.partite.perse++;
break;
case 2:
n.partite.vinte++;
n.punti += 3;
break;
}
fwrite(&n, sizeof(Nota),1, ptr);
fclose(ptr);
}
}
int CalcolaEsito(Match incontro){
int esito;
if(incontro.goal1 == incontro.goal2){
esito = 0;
}
else if(incontro.goal1 > incontro.goal2){
esito = 1;
}
else{
esito = 2;
}
return esito;
}
void DisputaFase(int valDati, Stringa percorso){
Match incontro;
int i,j;
for(i=1; i<=valDati; i++){
for(j=1; j<=valDati; j++){
if( j!= i){
DisputaMatch(&incontro, i, j);
AggiornaFile(percorso, incontro);
}
}
}
}
Nota CalcolaClassifica(Nota Vet[], int dim, Stringa percorso){
FILE *ptr;
Nota n;
int i = 0;
ptr = fopen(percorso, "rb");
if(ptr == NULL){
printf("File inesistente.\n");
}
else{
while(!feof(ptr)){
fread(&n, sizeof(Nota),1,ptr);
Vet[i] = n;
i++;
}
fclose(ptr);
}
ordina(Vet, dim);
return Vet[0];
}
void ordina(Nota *Vet, int dim){
int i,j;
int min;
Nota temp;
for(i=0; i<dim-1; i++){
min = i;
for(j=i+1; j<dim; j++){
if(Vet[min].punti < Vet[j].punti){
min = j;
}
}
if(min != i){
temp = Vet[min];
Vet[min] = Vet[i];
Vet[i] =temp;
}
}
}
void StampaClassifica(Nota Vet[], int dim){
int i,j;
printf("\n%s%15s%15s%18s%15s%15s%15s%15s\n", "Squadra", "Punteggio", " PartiteGiocate", "Vinte", "Perse", "Nulle", "Gsubiti", "Gfatti");
for(i=0; i<dim; i++){
printf("%7d%15d%15d%18d%15d%15d%15d%15d\n", Vet[i].squadra, Vet[i].punti, calcolaNPartite(Vet[i]), Vet[i].partite.vinte, Vet[i].partite.perse, Vet[i].partite.nulle,Vet[i].goal.subiti, Vet[i].goal.effettuati);
}
}
int calcolaNPartite(Nota nota){
int giocate;
giocate = nota.partite.nulle + nota.partite.perse + nota.partite.vinte;
return giocate;
}
int main(int argc, char *argv[]) {
FILE *ptr;
char percorso[300] = "C:\\file.dat";
Nota Vet[DIMMAX];
srand(time(NULL));
CreaFile(percorso, DIMMAX);
DisputaFase(DIMMAX, percorso);
CalcolaClassifica(Vet, DIMMAX, percorso);
StampaClassifica(Vet, DIMMAX);
return 0;
}
Note that fread and fwrite both advance the file pointer.
When wanting to read/modify/write in AggiornaFile you must fseek again before the write.
Also, be sure to use 0-based record indexing.
I have an input file a.txt:
1 abc 3
2 efgh 4.5
3 text 3
4 xyz 2
So basically, it has 3 columns, first one is int, second is text, and third is double. I need to read this file by rows (which actually works, I guess), but have some problems with writing only second and third column to another (b.txt) file. fprinft saves something like this:
0.000000
0.000000
0.000000
0.000000
xvæ$ 0.000000
instead of
abc 3
efgh 4.5
text 3
xyz 2
I simply need to save only the second and the third column from a.txt file to b.txt file. Here's my code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct mypair
{
char string[1024];
double number;
} mypair;
void zero_string(char *string, int n)
{
int i;
for(i=0; i<n; i++)
string[i] = '\0';
}
int row(FILE* f, struct mypair *p)
{
int num;
if(!feof(f))
{
if(fscanf(f,"%d %s %lf", &num, p->string, &p->number) == 3)
{
return 0;
}
}
else
{
return 1;
}
}
int main(int argc, char **argv)
{
int n = 5, status = 0, i = 0, j;
struct mypair array[5];
char file_in_name[255];
char file_out_name[255];
FILE *fin;
FILE *fout;
zero_string(file_in_name, 255);
zero_string(file_out_name, 255);
printf("Data file:\n> ");
scanf("%s", file_in_name);
printf("Out file:\n> ");
scanf("%s", file_out_name);
fin = fopen(file_in_name, "r");
fout = fopen(file_out_name, "w");
if( fin == NULL )
{
exit(-1);
}
if( fout == NULL )
{
exit(-1);
}
while(status != 1)
{
status = row(fin, &array[i]);
i ++;
fprintf(fout, "%s %lf\n", array[i].string, array[i].number);
if(i >= n)
break;
}
fclose(fin);
fclose(fout);
for(j=0; j<i; j++)
printf("%s %lf\n", array[i].string, array[i].number);
return 0;
}
I modified the code, now it works, thanks!
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct mypair
{
char string[1024];
double number;
} mypair;
void zero_string(char *string, int n)
{
int i;
for(i=0; i<n; i++)
string[i] = '\0';
}
int row(FILE* f, struct mypair *p)
{
int num;
if(!feof(f))
{
if(fscanf(f,"%d %s %lf", &num, p->string, &p->number) == 3)
{
return 0;
}
}
else
{
return 1;
}
}
int main(int argc, char **argv)
{
int n = 5, status = 0, i = 0, j;
struct mypair array[5];
char file_in_name[255];
char file_out_name[255];
FILE *fin;
FILE *fout;
zero_string(file_in_name, 255);
zero_string(file_out_name, 255);
printf("Data file:\n> ");
scanf("%s", file_in_name);
printf("Out file:\n> ");
scanf("%s", file_out_name);
fin = fopen(file_in_name, "r");
fout = fopen(file_out_name, "w");
if( fin == NULL )
{
exit(-1);
}
if( fout == NULL )
{
exit(-1);
}
printf("\n");
while(status != 1)
{
status = row(fin, &array[i]);
if(i >= n)
break;
else
{
if(status != -1)
fprintf(fout, "%s %lf\n", array[i].string, array[i].number);
}
i ++;
}
fclose(fin);
fclose(fout);
for(j=0; j<i; j++)
printf("%s %lf\n", array[j].string, array[j].number);
return 0;
}
In your bottom loop, you want to index your array by j, not i.
I need to sort a list of numbers in a file in a ascending order. I have done all the opening of the file and created my bubble sort function. But I'm stuck on how to make this all work together.
my inputefile.csv looks something like the following:
3,-4,-5,-8
10,30,50,-10
40,100,60,-2
void bubble_sort(char* line, int size);
int main(void)
{
FILE *file;
char* line;
int size = sizeof(line);
file = fopen("inputfile.csv", "r");
if(file == NULL)
{
printf("Unable to open the file");
}else
{
while(fgets(line, sizeof(line), file)
{
bubble_sort(line, size)
}
}
}
void bubble_sort(char* line, int size)
{
int temp, i, j;
for (i=0; i< size-1; i++)
{
for (j=0; j<size-1; j++)
{
if(line[j] > line[j+1])
{
temp = line[j];
line[j] = line[j+1];
line[j+1] = temp;
}
}
}
}
The number of lines is unknown and also each line has 4 integers separated by a comma. By my code you could say i am a newbee
#include <stdio.h>
#include <stdlib.h>
void bubble_sort(int *array, int size);
int main(void){
FILE *file;
char line[128];
if((file = fopen("inputfile.csv", "r")) == NULL){
printf("Unable to open the file");
return -1;
}
while(fgets(line, sizeof(line), file)){
int i, a[4], size = sizeof(a)/sizeof(*a);
sscanf(line, "%d,%d,%d,%d", &a[0], &a[1], &a[2], &a[3]);
bubble_sort(a, size);
for(i = 0; i < size; ++i){
printf("%d", a[i]);
if(i<size-1)
printf(", ");
}
printf("\n");
}
fclose(file);
return 0;
}
void bubble_sort(int *a, int size){
int i, temp, swap;
do{
for(swap=i=0;i<size-1;++i){
if(a[i]>a[i+1]){
swap = 1;
temp = a[i];
a[i] = a[i+1];
a[i+1] = temp;
}
}
--size;
}while(swap);
}