C Programming 201 file IO in from csv

preview_player
Показать описание
Register for free.
Рекомендации по теме
Комментарии
Автор

Excellent. Very helpful work. Thank you again.
For Linux users:


#include <stdio.h>
#include <stdlib.h> // for system ("clear"); call

int main (void) {
FILE *fp;
fp = fopen ("numbers.csv", "r");

int i;
int sum = 0;
float average;
int array[20];
float N = 20;

if (fp == NULL){
printf("\033[1;91m"); // set terminal text to bright red
printf("That file couldn't be opened for some reason\n");
printf("\033[0;40m"); // reset terminal colors to default
getchar(); // use getchar() instead of pause() for Windows
return 1;
}

for(i=0; i<N; i++){
fscanf(fp, "%d, ", &array[i]);
sum = sum + array[i]; // or you can write this sum += array[1]; as well
}
average = (float)sum/N; // I had an implicit declaration error in Linux defining N as a constant (const) - solved by defining it as float - sum is defined as an integer so average is set to compile as a float
fclose(fp);
fp = 0;
system ("clear"); // clear the terminal
printf("\033[1;32m"); // set terminal text to green
printf("The file numbers.csv has been successfully read.\n");
printf("\033[1;36m"); // set terminal text to cyan
printf("The average is %f\n", average);
printf("\033[1;32m"); // set terminal text to green
printf("Press any key to continue.\n");
printf("\033[0;40m"); // reset terminal colors to default
getchar(); // use getchar() instead of pause() for Windows
system ("clear"); // clear the terminal
return 0;
}

azvedicgurukul
Автор

Hi, how can I take strings from csv file?

deraim