Question

I am working on a C program for an introductory course and am currently stuck.

The program computes the approximate value of cos(x) via Taylor series expansion.

The catch is that it reads input from a dat. file which consists of a certain number of rows of three numbers each, containing information that is meant to be processed.

For instance, the dat. file might be:

    5
    1 -1 6
    2 1 .0001
    2 1.5 2
    ...

The first number of each row determines which method to compute cos(x), the second number determines the value of x, etc.

I process this file as a multidimensional array:

    int array[64][64], m;
    FILE *ifp
    ifp = fopen("cos_input.dat", "r");

    i = 0;
    fscanf(ifp, %d\n", &m); //takes the first value into int m
    while (fscanf(ifp, "%d %d %d\n", &array[i][0], &array[i][1], &array[i][2]) == 3) {
        i++;
    }

^This code (I think) puts the input data file into a m x 3 array.

Now I need to manipulate the elements of the array and then write them to another output dat. file, which takes the form, for example:

    x = 1
    x = 2
    x = 3
    x = 4
    ...

My notion to accomplish this is to first, implement my other functions with the values stored in the multi-dimensional array, which I believe I can do, just declaring each value of my array and throwing them into the computational blender that is my other functions. (e.g., power(array[3][2], array[1][2]);) Then I have to print them to a dat. file, which I have no clue how to do.

This is because I am very sketchy on my knowledge of pointers and the fprintf/fscanf functions.

When I am writing my final data it will consist of some loop which will spit out one value per line. What is the code to use in order to print this to cos_output.dat? Must I create a new pointer expression 'ofp' similar to how I created 'ifp' in order to open the input file and implement it with scanf?

This is my first and only step I can come up with so far.

    FILE *ofp; //output file pointer
    ofp = fopen("cos_output.dat", "w"); //the final output data file
    //.... how to print? T_T

Thanks, your help is very much appreciated!

(http://ece15.ucsd.edu/Labs/lab3.pdf) <- Link to the assignment (Problem 1) only if my explanations are unclear.

Was it helpful?

Solution

You can print to a file by doing something like

FILE *ofp; //output file pointer
ofp = fopen("cos_output.dat", "w"); //the final output data file
for (i = 0; i < 5; i++) {
    fprintf(ofp, "x = %d\n", i);
}

This will generate a cos_output.dat file contains

x = 0
x = 1
x = 2
x = 3
x = 4

You can modify this fprintf() statement to output whatever you want. See fprintf(3) for further details.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top