Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR C

fgets

#include <stdlib.h>
#include <stdio.h>
// Gets  the floating break points from text file.
int main()
{
    FILE *file_name;                              // File pointer
    file_name = fopen("audioP_Success.txt", "r"); // open file at path and set file name to it.
    // The infomation in the file
    /*  0.0	0.0
        0.5	0.2
        1.0	0.4
        1.5	0.6
        2.0	0.8
        2.5	1.0
        3.0	0.8
        3.5	0.6
        4.0	0.4
        4.5	0.2
        5.0	0.0
    */

    if (NULL == file_name) // Check if file has opened
    {
        perror("File not opened 
");
        return -1;
    }
    char str[100];
    float num1, num2;  // Place holders
    float y_Value[20]; // Array for y value
    float x_Value[20]; // Array for x value

    int i = 0;

    while (NULL != fgets(str, 99, file_name) && i < 99)
    { /*
        Checks to see if file is not equal to NULL
        Get info from file
        fgets in this case, will take up to 99 char or
        until it hits a new line, and then put them into str.
        */
        sscanf(str, "%f %f", &num1, &num2);
        // I have sscanf looking for the first two floats in the line of chars stored in str
        // then the value is assigned to num1 and num2

        y_Value[i] = num1; // now assign the value to a float array
        x_Value[i] = num2; // now assign the value to a float array

        i++;
    }
    int xy = 0;
    while (xy <= 10)
    { // print break point values to screen

        printf("
y value %0.2f  x value %0.2f
", y_Value[xy], x_Value[xy]);
        xy++;
    }

    fclose(file_name); // close file

    return 0;
}
// The printed result
/*
y value 0.00  x value 0.00

y value 0.50  x value 0.20

y value 1.00  x value 0.40

y value 1.50  x value 0.60

y value 2.00  x value 0.80

y value 2.50  x value 1.00

y value 3.00  x value 0.80

y value 3.50  x value 0.60

y value 4.00  x value 0.40

y value 4.50  x value 0.20

y value 5.00  x value 0.00
*/
 
PREVIOUS NEXT
Tagged: #fgets
ADD COMMENT
Topic
Name
2+7 =