C Programming Write a function using fscanf(), fprintf(), fopen(), and fclose()
ID: 3914015 • Letter: C
Question
C Programming
Write a function using fscanf(), fprintf(), fopen(), and fclose() to read a file (in.dat) which contains two vectors and output it to a new file called out.dat.
Let's say each vector has 4 elements, first vector (1, 2, 3, 4),second vector (6, 7, 8, 9). There should be two double type arrays to store the elements of the first vector and the elements of the second vector. In below example, in the first line, the number of elements is specified as a positive integer, which is 4 in this case. In the next line, it has the first element of the first vector and the first element of the second vector and so on.
The format in the in.dat file should be like this:
4
1 6
2 7
3 8
4 9
The format in out.dat file should be like this:
4
1.000 6.000
2.000 7.000
3.000 8.000
4.000 9.000
Explanation / Answer
// here is the full code
// output is attached
// plz comment if you need any clarification
// hit like if you liked it
// CODE
#include <stdio.h>
#include <stdlib.h>
void read(char* input, int* v1, int* v2, int* n) {
FILE* fp;
fp = fopen(input, "r"); // open the input file in the read mode
if(!fp) { // if file not opened exit the execution
printf("Failed to open input file ");
exit(-1);
}
fscanf(fp, "%d", n); // read the size of vectors to n
// allocate memory for v1 and v2
v1 = (int*) malloc((*n) * sizeof(int));
v2 = (int*) malloc((*n) * sizeof(int));
for(int i = 0; i < *n; i++) { // read the vectors to v1 and v2
fscanf(fp, "%d %d", &v1[i], &v2[i]);
}
fclose(fp); // close the input file
}
void write(char* output, int* v1, int* v2, int* n) {
FILE* fp;
fp = fopen(output, "w"); // open the output file in write mode
if(!fp) { // if file not opened exit the execution
printf("Failed to open output file ");
exit(-1);
}
fprintf(fp, "%d ", *n); // read the size of vectors to n
for(int i = 0; i < (*n); i++) { // write the vectors v1 and v2 into output file
//fflush(fp);
fprintf(fp, "%.3f %.3f ", (float)v1[i], (float)v2[i]);
}
fclose(fp); // close the output file
}
int main() {
int *v1, *v2; // declare two vectors v1 and v2
int n; // size of vectors
read("in.dat", v1, v2, &n); // read the vectors from in.dat
printf("Reading complete : in.dat");
write("out.dat", v1, v2, &n); // write the vectors to out.dat
printf("writing complete : out.dat");
return 0;
}
// OUTPUT
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.