//here's the structure
typedef struct student
{
int rno;
char name[20];
struct subject
{
int scode;
char sname[20];
int mark;
} sub[3];
int total;
float per;
} student;
student s1;
FILE *fp;
int j;
fp = fopen("mystudents.txt", "r");
while (fread(&s1, sizeof(student), 1, fp))
{
printf("\n%d \n%s", s1.rno, s1.name);
for (j = 0; j < 3; j++)
{
printf("\n%d", s1.sub[j].mark);
}
printf("\n%d", s1.total);
}
fclose(fp);
Content of my file :
101 brian 23 45 56 124
102 abhi 32 78 90 200
fread() is for reading binary files, not text files (unless you're reading into a string variable). You can use fscanf() to parse the text file.
student s1;
FILE *fp;
fp = fopen("mystudents.txt", "r");
while (fscanf(fp, "%d %s %d %d %d %d", &s1.rno, s1.name, &s1.sub[0].mark, &s1.sub[1].mark, &s1.sub[2].mark, &s1.total) > 0)
{
printf("\n%d \n%s", s1.rno, s1.name);
for (int j = 0; j < 3; j++)
{
printf("\n%d", s1.sub[j].mark);
}
printf("\n%d", s1.total);
}
fclose(fp);
Related
So my code involves reading in a PPM image and then storing it in an array so it can be saved in an new ppm file. Though I think there is a problem with my pointers that means its not actually reading the file. Also my code ends after allocating the memory for the array. Any help is much appreciated.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define maxheight 1080
#define maxwidth 1920
#define RGB_COMPONENT_COLOUR 255
#define pgmtype "P2"
#define ppmtype "P3"
typedef struct
{
int red, green, blue;
} PPMPixel;
typedef struct
{
int x, y;
} PPMImage;
typedef struct
{
int rgb_comp_colour;
char filetype[3];
int height;
int width;
} PPMHead;
/*PPMHead head[3];
{
head[3].filetype;
head[3].height;
head[3].width;
}*/
PPMHead head;
PPMHead* head_ptr = &head;
PPMPixel p;
PPMPixel* p_ptr = &p;
PPMPixel *data; //Defines pointer to PPMPixel
int **Array; //Double pointer defines as a pointer pointing to a pointer that is pointing to an integer
PPMPixel **RGBArray; //Double pointer defines as a pointer pointing to a pointer that is pointing to the PPMPixel structure
FILE *fp;
int r, g, b;
void headercheck ()
{
fscanf(fp, "%s %d %d %d", head.filetype, &head.width, &head.height, &head.rgb_comp_colour);
printf("%s %d %d %d", head.filetype, head.width, head.height, head.rgb_comp_colour);
if (head.width > maxwidth || head.height > maxheight)
{
printf("\tInvalid image size. The maximum value of image is 1920x1080.\n");
printf("\tImage size is %d x %d\n", head.width, head.height);
}
else
{
printf("\tImage size is valid\n");
printf("\tImage size is %d x %d\n", head.width, head.height);
}
if ((strcmp (head.filetype, pgmtype)!=0) && (strcmp (head.filetype, ppmtype)!=0))
{
printf("\tInvalid filetype\n");
}
else
{
if(strcmp (head.filetype, pgmtype)==0)
{
printf("\t File is PGM type image\n");
}
else
{
if(strcmp (head.filetype, ppmtype)==0)
{
printf("\t File is PPM type image\n");
}
}
}
if ((head.rgb_comp_colour == RGB_COMPONENT_COLOUR))
{
printf("\t Image is 8 bit\n");
}
else
{
if (head.rgb_comp_colour > RGB_COMPONENT_COLOUR)
{
printf("Maximum bit-depth is 8 bits\n");
}
else
{
printf("\tImage is not 8 bit\n");
}
}
}
int main(void)
{
char fname[100];
printf("Enter file name: ");
scanf("%s", fname);
fseek(stdin,0,SEEK_END);
fp = fopen(fname, "r");
if (fp == NULL)
{
printf("\tError while opening the file\n");
}
else
{
printf("\tReading in %s\n", fname);
}
headercheck();
if (strcmp (head.filetype, ppmtype)==0)
{
RGBArray = (PPMPixel **)malloc(head.height*sizeof(PPMPixel*)); //Points to malloc
if((RGBArray == NULL))
{
printf("Error allocating memory to the array");
}
else
{
printf("Memory allocated to the PPM array sucessfully");
}
for (int i=0;i<head.width;i++)
{
RGBArray[i] = (PPMPixel *)malloc(head.width*sizeof(PPMPixel));
}
printf("Error 2");
//Initialising each element
for (int j=0;j<head.height;j++)
{
for (int i=0;i<head.width;i++)
{
fscanf(fp, "%3d %3d %3d ", &p.red, &p.green, &p.blue); //Scans in integers of the address pointer to PPMPixel
data = &RGBArray[i][j]; //Defines data pointer pointing to address of RGBArray[i][j]
data->red = p.red; //Access member of PPMPixel structure to equal one of the three RGB channels
data->green = p.green;
data->blue = p.blue;
}
}
}
fclose(fp);
//Save PPM Array Into New PPM File
FILE *pf;
int i, j;
char fname2[100];
printf("Enter file name: ");
scanf("%s", fname2);
fseek(stdin,0,SEEK_END);
pf = fopen(fname2, "w");
if (pf == NULL)
{
printf("\tError while opening the file\n");
}
else
{
printf("\tWriting in %s\n", fname2);
}
for(j=0;j<head.height;j++)
{
fprintf(pf, "\n");
for(i=0;i<head.width;i++)
{
fprintf(pf, "%3d ", RGBArray[i][j].red);
fprintf(pf, "%3d ", RGBArray[i][j].green);
fprintf(pf, "%3d ", RGBArray[i][j].blue);
//fprintf(pf, "%3d ", (RGBArray+j*head.width + i)*r);
//fprintf(pf, "%3d ", (RGBArray+j*head.width + i)*g);
//fprintf(pf, "%3d ", (RGBArray+j*head.width + i)*b);
}
}
fclose(pf);
free(RGBArray);
RGBArray = NULL;
for(int i=0;i<head.width;i++)
{
free(RGBArray[i]);
RGBArray[i] = NULL;
}
return 0;
}
You mainly mixed width and height, but there are other issues.
width is the number of columns
height is the number of rows
The C two dimensional array in memory order is Row Major.
The convention for storing an image in memory is "by rows".
The indexing is RGBArray[col][row] (in your code it should be RGBArray[j][i]).
Illustration:
RGBArray[0][0] RGBArray[0][14]
| |
V V
<--- width --->
RGBArray[0] -> ############### ^
RGBArray[1] -> ############### |
RGBArray[2] -> ############### height
RGBArray[3] -> ############### |
RGBArray[4] -> ############### V
I used the following PPM text file for testing (in.ppm):
P3
# ppm comment
4 3
255
1 2 3 11 12 13 21 22 23 31 32 33
101 102 103 111 112 113 121 122 123 131 132 133
201 202 203 211 212 213 221 222 223 231 232 233
Corrected code (please read the comments):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define maxheight 1080
#define maxwidth 1920
#define RGB_COMPONENT_COLOUR 255
#define pgmtype "P2"
#define ppmtype "P3"
typedef struct
{
int red, green, blue;
} PPMPixel;
typedef struct
{
int x, y;
} PPMImage;
typedef struct
{
int rgb_comp_colour;
char filetype[3];
int height;
int width;
} PPMHead;
PPMHead head;
PPMHead* head_ptr = &head;
PPMPixel p;
PPMPixel* p_ptr = &p;
PPMPixel *data; //Defines pointer to PPMPixel
int **Array; //Double pointer defines as a pointer pointing to a pointer that is pointing to an integer
PPMPixel **RGBArray; //Double pointer defines as a pointer pointing to a pointer that is pointing to the PPMPixel structure
FILE *fp;
int r, g, b;
void headercheck()
{
char tmp[201]; //Temporary string.
fscanf(fp, "%2s", head.filetype); //%2s ensures that no more than two characters are read.
fscanf(fp, "%200s", tmp);
if (tmp[0] == '#')
{
//The second line may be a comment starting with '#'
fgets(tmp, 200, fp); //Skip the comment.
fscanf(fp, "%d", &head.width);
}
else
{
//If not a comment, read width from tmp.
sscanf(tmp, "%d", &head.width);
}
//fscanf(fp, "%s %d %d %d", head.filetype, &head.width, &head.height, &head.rgb_comp_colour);
fscanf(fp, "%d %d", &head.height, &head.rgb_comp_colour);
printf("%s %d %d %d", head.filetype, head.width, head.height, head.rgb_comp_colour);
if (head.width > maxwidth || head.height > maxheight)
{
printf("\tInvalid image size. The maximum value of image is 1920x1080.\n");
printf("\tImage size is %d x %d\n", head.width, head.height);
}
else
{
printf("\tImage size is valid\n");
printf("\tImage size is %d x %d\n", head.width, head.height);
}
if ((strcmp(head.filetype, pgmtype) != 0) && (strcmp(head.filetype, ppmtype) != 0))
{
printf("\tInvalid filetype\n");
}
else
{
if (strcmp(head.filetype, pgmtype) == 0)
{
printf("\t File is PGM type image\n");
}
else
{
if (strcmp(head.filetype, ppmtype) == 0)
{
printf("\t File is PPM type image\n");
}
}
}
if ((head.rgb_comp_colour == RGB_COMPONENT_COLOUR))
{
printf("\t Image is 8 bit\n");
}
else
{
if (head.rgb_comp_colour > RGB_COMPONENT_COLOUR)
{
printf("Maximum bit-depth is 8 bits\n");
}
else
{
printf("\tImage is not 8 bit\n");
}
}
}
int main(void)
{
const char *fname = "in.ppm";
//char fname[100];
//printf("Enter file name: ");
//scanf("%s", fname);
//fseek(stdin, 0, SEEK_END);
fp = fopen(fname, "r");
if (fp == NULL)
{
printf("\tError while opening the file\n");
}
else
{
printf("\tReading in %s\n", fname);
}
headercheck();
if (strcmp(head.filetype, ppmtype) == 0)
{
RGBArray = (PPMPixel **)malloc(head.height * sizeof(PPMPixel*)); //Points to malloc
if ((RGBArray == NULL))
{
printf("Error allocating memory to the array\n");
}
else
{
printf("Memory allocated to the PPM array successfully\n");
}
//for (int i = 0; i < head.width; i++)
for (int i = 0; i < head.height; i++) //Iterate height rows
{
RGBArray[i] = (PPMPixel *)malloc(head.width * sizeof(PPMPixel));
if ((RGBArray[i] == NULL))
{
printf("Error allocating memory to the array\n");
}
}
//printf("Error 2");
//Initializing each element
for (int j = 0; j < head.height; j++)
{
for (int i = 0; i < head.width; i++)
{
fscanf(fp, "%3d %3d %3d ", &p.red, &p.green, &p.blue); //Scans in integers of the address pointer to PPMPixel
//data = &RGBArray[i][j]; //Defines data pointer pointing to address of RGBArray[i][j]
data = &RGBArray[j][i]; //The row index comes first - (use [j][i] instead of [i][j])
data->red = p.red; //Access member of PPMPixel structure to equal one of the three RGB channels
data->green = p.green;
data->blue = p.blue;
}
}
}
fclose(fp);
//Save PPM Array Into New PPM File
FILE *pf;
int i, j;
//char fname2[100];
//printf("Enter file name: ");
//scanf("%s", fname2);
//fseek(stdin, 0, SEEK_END);
const char *fname2 = "out.ppm";
pf = fopen(fname2, "w");
if (pf == NULL)
{
printf("\tError while opening the file\n");
}
else
{
printf("\tWriting in %s\n", fname2);
}
//Write the PPM header
////////////////////////////////////////////////////////////////////////////
fprintf(fp, "%s\n", head.filetype);
fprintf(fp, "%d %d\n", head.width, head.height);
fprintf(fp, "%d\n", head.rgb_comp_colour);
////////////////////////////////////////////////////////////////////////////
for (j = 0; j < head.height; j++)
{
//fprintf(pf, "\n");
for (i = 0; i < head.width; i++)
{
//fprintf(pf, "%3d ", RGBArray[i][j].red);
//fprintf(pf, "%3d ", RGBArray[i][j].green);
//fprintf(pf, "%3d ", RGBArray[i][j].blue);
fprintf(pf, "%3d ", RGBArray[j][i].red); //row index comes first - use [j][i] instead of [i][j]
fprintf(pf, "%3d ", RGBArray[j][i].green);
fprintf(pf, "%3d ", RGBArray[j][i].blue);
}
fprintf(pf, "\n");
}
fclose(pf);
//free(RGBArray);
//RGBArray = NULL;
for (int i = 0; i < head.height; i++)
{
free(RGBArray[i]);
RGBArray[i] = NULL;
}
free(RGBArray); //Free RGBArray after free RGBArray[i]
RGBArray = NULL;
return 0;
}
Output file (out.ppm):
P3
4 3
255
1 2 3 11 12 13 21 22 23 31 32 33
101 102 103 111 112 113 121 122 123 131 132 133
201 202 203 211 212 213 221 222 223 231 232 233
Thanks for all the answers, after the corrections the code did not work for a stupid error ... I opened both files with the same file pointer "database" ...
I've read dozens of questions like this but I can't get out of it, I'm going crazy.
The exercise that I have to do asks me to organize the items of a list in a file .txt that has elements of the type: Name Surname Age Wage, in alphabetical order according to the surname.
I have already created a function to insert the elements into the file and it works well.
I then went to the function to organize them but the process stops after the fscanf, and putting some test printf I saw that no values are assigned to the strings or that are assigned absurd numbers.
Please help ... thanks.
This is the code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define MAX 64
#define MAXFILE 100
void insert();
int fullcheck();
void sort();
typedef struct {
char name[MAX];
char surname[MAX];
int age;
double wage;
} data;
int main() {
insert();
return EXIT_SUCCESS;
}
void insert() {
char c;
int i;
data tmp;
FILE* database;
if ((fullcheck())>MAXFILE-1)
printf("Errore: database pieno.\n");
else {
database=fopen("database.txt", "a");
printf("Nome: ");
fgets(tmp.name, MAX, stdin);
tmp.name[strlen(tmp.name)-1]='\0';
printf("Cognome: ");
fgets(tmp.surname, MAX, stdin);
tmp.surname[strlen(tmp.surname)-1]='\0';
for (i=0; i<strlen(tmp.surname); i++) {
if (tmp.surname[i]==' ')
tmp.surname[i]='#';
}
printf("Eta': ");
scanf("%d", &tmp.age);
printf("Salario: ");
scanf("%lf", &tmp.wage);
while((c=getchar())!='\n');
fprintf(database, "%s %s %d %.0lf \n", tmp.name, tmp.surname, tmp.age, tmp.wage);
fflush(database); fclose(database);
if ((fullcheck())>1)
sort();
}
}
int fullcheck() {
char c;
int r=0;
FILE* database;
if ((database=fopen("database.txt", "r"))==NULL) {
return 0;
}
else {
while((c=getc(database))!=EOF) {
if(c=='\n')
r++;
}
return r;
}
}
void sort() {
char tmpstr[MAX];
int len=fullcheck(), i, a, b;
data tmp[len];
FILE* database;
FILE* sorted;
database=fopen("database.txt", "r");
database=fopen("sorted.txt", "w");
for (i=0; i<=len; i++) {
fscanf(database, "%s %s %d %lf \n", &tmp[i].name, &tmp[i].surname, &tmp[i].age, &tmp[i].wage);
}
for (a=0 ; a<(len-1); a++) {
for (b=0; b<(len-1); b++) {
if ((tolower(tmp[b].surname[0]))>(tolower(tmp[b+1].surname[0]))) {
strcpy(tmpstr, tmp[b].surname);
strcpy(tmp[b].surname, tmp[b+1].surname);
strcpy(tmp[b+1].surname, tmpstr);
}
}
}
for (a=0; a<(len-1); a++) {
fprintf(sorted, "%s %s %d %.0lf \n", tmp[a].name, tmp[a].surname, tmp[a].age, tmp[a].wage);
}
fflush(database); fclose(database); remove("database.txt");
fflush(sorted); fclose(sorted); rename("sorted.txt", "database.txt");
}
Off by 1
Code attempts to read into len+1 elements of tmp[].
data tmp[len];
for (i=0; i<=len; i++) { // too many
fscanf(database, "%s %s %d %lf \n", &tmp[i].name, &tmp[i].surname, &tmp[i].age, &tmp[i].wage);
}
I saw that no values are assigned to the strings (OP)
Better code would use width limits and test fscanf() result before using the data scanned.
// v---- < not <=
for (i=0; i<len; i++) {
if (fscanf(database, "%63s %63s %d %lf",
&tmp[i].name, &tmp[i].surname, &tmp[i].age, &tmp[i].wage) != 4) {
// ^^^^ test!
break;
}
Even better code would read a line with fgets() into a stirng and then attempt to parse the string.
Off by 2
Code's attempt to find number of lines can be short by 1 if the last line does not end with a '\n'.
Alternative
size_t fullcheck(void) {
FILE* database = fopen("database.txt", "r");
if (database == NULL) {
return 0;
}
int previous = '\n';
int c;
size_t r=0;
while((c=getc(database))!=EOF) {
if (previous == '\n') r++;
previous = c;
}
fclose(database);
return r;
}
Missing fclose()
fullcheck() doesn't close the file after opening it.
int
Use an int to distinguish the typically 257 different returns values of fgetc(). Note when char` is unsinged, OP's code is an infinite loop.
More woes
The loop to print the sorted list is off-by-one, too short. And the sorting itself only looks at the first letter of each name, should use strcmp.
#user3386109
Maybe more?
Make sure to close the file here, before every return:
int fullcheck() {
char c;
int r=0;
FILE* database;
if ((database=fopen("database.txt", "r"))==NULL) {
fclose(database);
return 0;
}
else {
while((c=getc(database))!=EOF) {
if(c=='\n')
r++;
}
fclose(database);
return r;
}
}
And also a little bit fixing in the loop_counters here:
void sort() {
char tmpstr[MAX];
int len=fullcheck(), i, a, b;
data tmp[len];
FILE* database;
FILE* sorted;
database=fopen("database.txt", "r");
sorted=fopen("sorted.txt", "w+");
for (i=0; i<len; i++) {
fscanf(database, "%s %s %d %lf \n", &tmp[i].name, &tmp[i].surname, &tmp[i].age, &tmp[i].wage);
printf("%s", tmp[b+1].surname);
system("pause");
}
for (a=0 ; a<(len); a++) {
for (b=0; b<(len); b++) {
if ((tolower(tmp[b].surname[0]))>(tolower(tmp[b+1].surname[0]))) {
strcpy(tmpstr, tmp[b].surname);
strcpy(tmp[b].surname, tmp[b+1].surname);
strcpy(tmp[b+1].surname, tmpstr);
printf("%s", tmp[b+1].surname);
system("pause");
}
}
}
for (a=0; a<(len); a++) {
fprintf(sorted, "%s %s %d %.0lf \n", tmp[a].name, tmp[a].surname, tmp[a].age, tmp[a].wage);
}
fclose(sorted);
fclose(database);
}
#include <stdio.h>
int getIntegers(char *filename,int a[]);
int main(void) {
/////
FILE *fp;
char file[10] = "random.txt";
fp = fopen(file, "w");
fprintf(fp, "1 2 -34 56 -98 42516547example-34t+56ge-pad12345\n");
fclose(fp);
/////
int i;
int a[100];
int n = getIntegers(file,a);
//Here i want to print out what i got from getIntegers. What it should put out = "1 2 -34 56 -98 42516547 -34 56 12345"
if (n > 0)
{
puts("found numbers:");
for(i = 0;i < n; i++)
{
printf("%d ",a[i]);
}
putchar('\n');
}
return 0;
}
int getIntegers(char *filename, int a[])
{
int c, i;
FILE *fp;
fp = fopen(filename, "r");
//I want what this code does to be done with the commented code under it. This will give "1 2 -34 56 -98 42516547"
while (fscanf(fp,"%d",&i)==1)
{
printf("%d ",i);
}
fclose(fp);
// I want this code to give "1 2 -34 56 -98 42516547 -34 56 12345"
// while ((c = fgetc(fp)) != EOF)
// {
// for(i = 0; i < c;i++)
// {
// fscanf(fp, "%1d", &a[i]);
// }
// }
// return i;
}
I have a file with numbers and words/letters in it. With this code I get the integers untill first letter, but i want to continue until EOF. And then return those numbers and print them out in main. I tried but could not get it to work. What should/could i do to get this working? Or what am I doing wrong.
Multiple issues:
int getIntegers() does not return any value. Code does not save anything in a[]. Array limits not enforced.
Commented code does not check the return value of fscanf().
Code needs to consume 1 character when fscanf() returns 0 and then try again.
When fscanf(fp, "%d", &a[i]) returns 0, it means the input is not numeric and fscanf() did not consume any of the non-numeric input. So read 1 character and try again.
#include <stdio.h>
#define N 100
int getIntegers(char *filename, int a[], int n);
int main(void) {
FILE *fp;
char file[] = "random.txt";
fp = fopen(file, "w");
if (fp == NULL) {
fprintf(stderr, "Unable to open file for writing\n");
return -1;
}
fprintf(fp, "1 2 -34 56 -98 42516547example-34t+56ge-pad12345\n");
fclose(fp);
int a[N];
int i;
int n = getIntegers(file, a, N);
puts("found numbers:");
for (i = 0; i < n; i++) {
printf("%d ", a[i]);
}
putchar('\n');
return 0;
}
int getIntegers(char *filename, int a[], int n) {
int i;
FILE *fp = fopen(filename, "r");
if (fp) {
for (i = 0; i < n; i++) {
int cnt;
do {
cnt = fscanf(fp, "%d", &a[i]);
if (cnt == EOF) { fclose(fp); return i; }
if (cnt == 0) fgetc(fp); // Toss 1 character and try again
} while (cnt != 1);
// printf("%d ", i);
}
fclose(fp);
}
return i;
}
Output
found numbers:1 2 -34 56 -98 42516547 -34 56 12345
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 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;
}