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.
Related
#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
i have to read from a file which contains names and scores the results of a contest but the function fscanf is not working properly.. Does it have to do with newlines or something?
I'll leave below the code and the screenshots of the issue i'm having.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct contest
{
char name[25];
int score;
}Contest;
int main(int argc, const char * argv[]) {
Contest players[100];
FILE *fp;
fp = fopen("contest.txt", "r");
if(fp == NULL)
{
fprintf(stderr, "Error: failed to open the file\n");
exit(EXIT_FAILURE);
}
int cnt = 0;
while(fscanf(fp, "%s %d", players[cnt].name, &players[cnt].score) != EOF)
{
++cnt;
}
char temp[25];
for(int t = 0; t < cnt; ++t)
{
for(int u = 0; u < cnt; ++u)
{
if(strcasecmp(players[t].name, players[u].name) > 0)
{
strcpy(temp, players[t].name);
strcpy(players[t].name, players[u].name);
strcpy(players[u].name, temp);
}
}
}
for(int t = 0; t < cnt; ++t)
{
fprintf(stdout, "Name : %s Score : %d\n", players[t].name, players[t].score);
}
fclose(fp);
return 0;
}
Input:
Randal 34
Leonel 67
Vaughn 100
Missy 68
Cristopher 92
Dagmar 102
Blondell 88
Milly 83
Darrel 12
Josh 71
Output:
You've just made two little mistakes: (1) forgot to also swap the scores and (2) did the wrong comparison in the strcasecmp. For the rest, it's all working fine here.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
typedef struct contest
{
char name[32];
int score;
} Contest;
int main()
{
Contest players[100];
FILE *fp = fopen("contest.txt", "r");
assert(fp);
int cnt = 0;
while(fscanf(fp, "%s %d", players[cnt].name, &players[cnt].score) != EOF)
++cnt;
for(int i = 0; i < cnt; ++i)
{
for(int j = 0; j < cnt; ++j)
{
if(strcasecmp(players[i].name, players[j].name) < 0)
{
int tempScore = players[i].score;
players[i].score = players[j].score;
players[j].score = tempScore;
char tempName[32];
strcpy(tempName, players[i].name);
strcpy(players[i].name, players[j].name);
strcpy(players[j].name, tempName);
}
}
}
for(int i = 0; i < cnt; ++i)
fprintf(stdout, "Name : %s Score : %d\n", players[i].name, players[i].score);
fclose(fp);
return 0;
}
I have an Instance File from which I need to store the NUM_PT and all the respective co-ordinates in the form of a 2D array system (personal choice so I can access them easily). I am able to retrieve the NUM_PT but I am stuck at reading the successive cordinates into my array.
HERE IS WHAT I HAVE DONE
/* Assignment 2 */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include <ctype.h>
#define MAXS 256
int main(int argc, char *argv[])
{
int num_pt;
int inputfile = 0, outputfile = 0, i;
for (i = 1; i < argc; i++)
{
if (strcmp (argv[i], "-i") == 0)
inputfile = i+1;
if (strcmp (argv[i], "-o") == 0)
outputfile = i+1;
}
if (inputfile == 0)
{
/* invalid command line options */
printf("\nIncorrect command-line...\n");
printf("> %s [-i inputfile [-o outputfile]]\n\n", argv[0]);
exit(0);
}
FILE *fp;
fp = fopen(argv[inputfile], "r");
int count = 0;
if (fp == 0)
{
printf("\nCould not find %s\n", argv[inputfile]);
exit(0);
}
char line[MAXS];
while (fgets(line, sizeof line, fp) != NULL)
{
if (count == 4)
{
fscanf(fp, "%d", &num_pt);
break;
}
else
count++;
}
int arr[num_pt][1];
while (fgets(line, sizeof line, fp) != NULL)
{
if (count == 5)
{
int k, j, cord;
for (k = 0; k < num_pt; k++)
{
for (j = 0; j < num_pt; j++)
{
while (fscanf(fp, "%d%d", &cord) > 0)
{
arr[k][j] = cord;
j++;
}
}
}
}
}
fclose(fp)
return 0;
}
After retrieving NUM_PT i tried reinitializing the count to 5 because the cordinates start from **LINE 6* in the file.
ERROR FROM COMPILER
Language: c99 ; Compiler: gcc
sample for "Storing numbers as (x, y) cordinates from a file" (It is better not to fix the reading position)
#include <stdio.h>
typedef struct point {
int x, y;
} Point;
int readPoint(FILE *fp, Point *p);
int readInt(FILE *fp, int *n);
int main(void){
FILE *fp = fopen("instance10_001.txt", "r");
Point p;
int MAX_X, MAX_Y;
readPoint(fp, &p);
MAX_X = p.x;
MAX_Y = p.y;
printf("MAX_X:%d, MAX_Y:%d\n", MAX_X, MAX_Y);
int NUM_PT;
readInt(fp, &NUM_PT);
printf("NUM_PT:%d\n", NUM_PT);
Point arr[NUM_PT];
for(int i = 0; i < NUM_PT; ++i){
readPoint(fp, &arr[i]);
printf("Point(%d, %d)\n", arr[i].x, arr[i].y);
}
fclose(fp);
}
int readLine(FILE *fp, char *buff, int buff_size){
while(fgets(buff, buff_size, fp)){
if(*buff == '#' || *buff == '\n')
continue;
return 1;
}
return 0;
}
#define LINE_MAX 128
int readPoint(FILE *fp, Point *p){
char buff[LINE_MAX];
if(readLine(fp, buff, sizeof buff)){
return 2 == sscanf(buff, "%d %d", &p->x, &p->y);
}
return 0;
}
int readInt(FILE *fp, int *n){
char buff[LINE_MAX];
if(readLine(fp, buff, sizeof buff)){
return 1 == sscanf(buff, "%d", n);
}
return 0;
}
Totals different for same file when executed.
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX_FILE_NAME 100
#define RUNS 1
int main() {
int num,i;
FILE *fp;
char*s, buf[1024];
int count =0;
char c;
char filename[MAX_FILE_NAME];
printf("Enter filename: ");
scanf ("%s",filename);
if ((fp =fopen(filename, "r")) == NULL) {
printf("Error");
exit(1);
}
fscanf(fp,"%d",&num);
for (c = getc(fp); c!= EOF; c = getc(fp))
{
if (c == '\n'){
count = count+1;
}
}
printf("%s has %d numbers \n", filename, count);
int f;
printf("Choose from the options how many processes you want to use [1,2,4]: ");
scanf("%i", &f);
printf("%i processes \n", f);
int fds[f+1][2];
int numb[count];
int x,k;
time_t start, finish;
start = time(NULL);
for(i = 0; i < RUNS; i++)
{
pipe(fds[f]);
for( x = 0; x<f; x++)
{
pipe(fds[x]);
int ind[2];
ind[0] = ((x)*(count/f));
ind[1] = ((x+1)*(count/f));
write(fds[x][1], &ind, 2* sizeof(int));
if (fork() ==0)
{
int t =0;
int ind2[2];
read(fds[x][0], &ind2, 2*sizeof(int));
for( k = ind2[0]; k<ind2[1]; k++)
{
t += numb[k];
}
write(fds[f][1], &t, sizeof(int));
exit(0);
}
}
int m, tmp, total;
total = 0;
for( m = 0; m < f; m++)
{
for( m = 0; m < f; m++)
{
read(fds[f][0], &tmp, sizeof(int));
sleep(5);
total += tmp;
}
printf("DOne calc \n");
printf("Total: %i \n", total);
}
finish = time(NULL);
float runtime = (float)((finish-start)/RUNS);
printf("runtime: %f \n", runtime);
fclose(fp);
return 0;
}
You get random result for the same input because the calculation based on uninitialized int numb[count]; values.
According to the C99 standard, section 6.7.8.10:
If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate.
Because of it int numb[count]; contains some random junk from memory. To get predictive results use explicit initialization:
#include <string.h> // memset
int numb[count];
memset (numb, 0, sizeof(numb)); // Zero-fills
Use the code bellow to put numbers from filename file into numb:
int i = 0;
char line[1024];
fseek(fp, 0, SEEK_SET);
while(fgets(line, sizeof(line), fp) )
{
if( sscanf(line, "%d", &numb[i]) == 1 ) // One number per line
{
++i;
}
}
I am trying to do duplicate elimination from clients.txt (which has 7 names and surnames, some of them are repeated). In the end of file it writes the output to output.dat file. I did not get any error during the compiling but when i try to run it, it gives "003.exe stopped working" error. (003.c is C project name)
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct names
{
char name[25];
char surname[25];
};
int main()
{
int i, j;
char a[1] = {""};
struct names name[200];
FILE *file;
FILE *file2;
file = fopen("clients.txt", "r");
if (ferror(file))
{
printf ("File could not be opened");
}
while (fscanf(file, "%s", a) == 2)
{
i = 0;
fscanf(file, "%s %s", name[i].name, name[i].surname);
i++;
}
for (i = 0; i < 200; i++)
{
for (j = 0; j < 200; j++)
{
if (i != j && strcmp(name[i].name, name[j].name) == 0 && strcmp(name[i].surname, name[j].surname) == 0 )
{
strcpy(name[j].name, a);
strcpy(name[j].surname, a);
}
}
}
fclose(file);
file2 = fopen("output.dat", "w");
{
for (i = 0; i < 200; i++)
{
if ( strcmp(name[i].name, "") == 1 )
{
fprintf(file, "%s %s\n", name[i].name, name[i].surname);
}
}
}
fclose(file2);
system("pause");
return 0;
}
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct names {
char name[25];
char surname[25];
};
int isEqual(struct names *a, struct names *b){
return strcmp(a->name, b->name) == 0 && strcmp(a->surname, b->surname)==0;
}
int main(){
int i, j;
struct names name[200], a;
FILE *file;
file = fopen("clients.txt", "r");
if (!file){//ferror can't use to fopen
printf ("File could not be opened");
return -1;
}
i=0;
while (fscanf(file, "%24s %24s", a.name, a.surname) == 2){
int dup = 0;
for(j=0; j < i ;++j){
if(dup=isEqual(&a, &name[j]))
break;
}
if(!dup)//!dup && i<200
name[i++] = a;
}
fclose(file);
file = fopen("output.dat", "w");
for (j = 0; j < i; ++j){
fprintf(file, "%s %s\n", name[j].name, name[j].surname);
}
fclose(file);
system("pause");
return 0;
}