Hello,
I'm trying to print out a column in a data file, this is the contents of the data file:
Code:
1 2 3 4
5 6 7 8
9 10 11 12
This is the source code:
Code:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
void main()
{
/* Declare Local Variables */
FILE *fptr; // File pointer for reading data file
int numTraces = 4; // Number of traces in file to be analysed
int numSamples = 7661; // Number of samples in file to be analysed
int i = 0;
int trace; // Trace number to analyse
float sample; // Sample being scanned into program
char prompt; // Prompt to hold program
/* Input column to analyse */
printf("Please enter trace number to analyse (1 - %d): ",numTraces);
scanf("\n%d", &trace);
/* Open program.dat file */
fptr = fopen("data.txt", "r"); // For read access only
if (fptr == NULL)
{
printf("Unable to find file: [data.txt]\n\n\r"); // Error if the program.dat file can't be found
/* Wait for enter key to close */
printf("Press Enter to close the program.");
getchar();
exit(1);
}
i = trace; // Initialise i to 0 + trace number to analyse
/* Scan Information from File */
while (fscanf(fptr, "%f", &sample) != EOF) // Loop until end of file marker, i.e. no more values to calculate
{
if (i % numTraces == 0)
{
printf("%f\n\r", sample);
}
i++;
}
/* Clean up */
fclose(fptr);
/* Wait for enter key to close */
printf("Press any key followed by Enter to close the program.");
scanf("\n%c", &prompt);
exit(1);
}
So the user enters a number between 1 and 4 and then it should print on each line the numbers from that column.
It's sort of working... by this I mean when you ask for:
- column 1 it prints column 4
- column 2 it prints column 3
- column 3 it prints column 2
- column 4 it prints column 1
It's like it's transposing it somehow? I'm sure it's something simple, prehaps to do with the if statement that wraps around the printf statement?
I look forward to hearing from you.
Kind Regards
Edward