Question:
C programming text files helps?
Siaw
2011-10-17 06:08:41 UTC
First lets view the question....

Write a program that reads the input from the text file, number.data, and then writes these data to a new file named "output.txt". Your program must apply array and structure in a text files.
_______________________________________________________________________________

Note that the number.data files include below information...(I already type in those information into a notepad and save in .data)
1 Ng 4.4
2 Lee 4.5
3 Lau 6.6
_______________________________________________________________________________

My coding so far...

#include
#include
#include

struct PayRecord {

long id;
char name[20];
double rate;
};

int main(void) {

FILE *fpin, *fpout;

int i=0, j;
char ch;

struct PayRecord pr[10] = {0};

fpin = fopen("number.dat","r");
fpout = fopen("numberout.txt","w");

if((!fpin) || (!fpout))
printf("Cannot open number.data.\n");

else {

while(fscanf(fpin,"%ld", &pr[i].id)==1) {
fscanf(fpin,"%s %lf", &pr[i].name, &pr[i].rate);
i++;
}

for(j=0; j printf("%d", pr[j].id);
printf("%s", pr[j].name);
printf("%lf\n", pr[j].rate);
}

while((ch = getc(fpin)) != EOF)
fputc(ch,fpout);

fclose(fpout);
fclose(fpin);

}

return 0;

}

___________________________________________________________________________

I successful read this number.data and change them into structure form and array form...but now I can't write them into a new text files? Any help? Very thanks.
Three answers:
roger
2011-10-17 08:14:30 UTC
if you are writing to a new text file then you should use fprintf(...)

look here :

http://www.cplusplus.com/reference/clibrary/cstdio/fprintf/

it will give you formatted text output to a file.



you opened fpout in text mode so you want to write to it in text mode.

fwrite will write in binary (not text) and is not what you want in a .txt file



for(j=0; j
fprintf(fpout ,"%ld %s %lf\n", pr[j].id,pr[j].name,pr[j].rate);



}
Rainmaker
2011-10-17 06:15:44 UTC
Here's how you write a structure to a file:



fwrite(&pr, sizeof(pr), 1, fpout);
2016-10-14 02:56:40 UTC
upload a char to save the entire call : char fullname[f7177163c833dff4b38fc8d2872f1ec6f7177163c833dff4b38fc8d2872f1ec6]; upload strcpy and srcat to combine the 1st and final call : strcpy(fullname,call.fname); strcat(fullname," "); strcat(fullname,call.lname); strcat(fullname,".txt"); Open the record like this: fp=fopen(fullname,"a");


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...