Reading from csv file in C causing input to not print - c

I am trying to read data from a csv file input below:
0, 0
5, 0
7, 0
This input is supposed to be x and y coordinates where x= 0 and y =0 and x=5 and y=5 and so on....
What i have tried
I am trying to print the numbers and then store each one. I can't store them or print them correctly as I am new to C and I am finding it difficult
Required output:
x:0 y:0
x:5 y:0
x:7 y:0
This is my code below:
#include <stdio.h>
#include <stdlib.h>
#include <curses.h>
#include <string.h>
int main()
{
FILE* fp = fopen("points.csv", "r");
if (!fp)
printf("Can't open file\n");
else {
char buffer[1024];
int row = 0;
int column = 0;
int distance;
while (fgets(buffer,
1024, fp)) {
column = 0;
row++;
if (row == 1)
continue;
// Splitting the data
char* value = strtok(buffer, ",");
while (value) {
// Column 1
if (column == 0) {
printf("x:");
}
// Column 2
if (column == 1) {
printf("\ty:");
}
printf("%s", value);
value = strtok(NULL, ", ");
column++;
}
// distance = ((x2-x1) *(x2-x1)) + ((y2-y1) * (y2-y1));
printf("\n");
}
fclose(fp);
}
return 0;
}

Since your file contains only two columns, you can write it this way using sscanf():
#include <stdio.h>
#include <string.h>
int main()
{
FILE *fp = fopen("file", "r");
if (!fp) {
fprintf(stderr, "Can't open file\n");
return 1;
}
char line[1024];
int x, y;
while (fgets(line, sizeof line, fp)) {
line[strcspn(line, "\n")] = '\0'; // Replace '\n' read by fgets() by '\0'
if (sscanf(line, "%d, %d", &x, &y) != 2) {
fprintf(stderr, "Bad line\n");
}
printf("x:%d\ty:%d\n", x, y);
}
fclose(fp);
}

Related

Load string containing words from file

I need to load strings from file into a struct array.
CORRECT OUTPUT:
4
Sarajevo,345123
Tuzla,123456
Mostar,101010
Banja Luka,234987
MY OUTPUT:
1
Sarajevo 345123
Tuzla 123456
Mostar 101010
Banja Luka 234987,544366964
Code:
#include <stdio.h>
#include <string.h>
struct City {
char name[31];
int number_of_citizen;
};
int load(struct City cities[100], int n) {
FILE *fp = fopen("cities.txt", "r");
int i = 0;
while (fscanf(fp, "%[^,]s %d\n", cities[i].name, &cities[i].number_of_citizen)) {
i++;
if (i == n)break;
if (feof(fp))break;
}
fclose(fp);
return i;
}
int main() {
int i, number_of_cities;
struct City cities[10];
FILE* fp = fopen("cities.txt", "w");
fputs("Sarajevo 345123", fp); fputc(10, fp);
fputs("Tuzla 123456", fp); fputc(10, fp);
fputs("Mostar 101010", fp); fputc(10, fp);
fputs("Banja Luka 234987", fp);
fclose(fp);
number_of_cities = load(cities, 10);
printf("%d\n", number_of_cities);
for (i = 0; i < number_of_cities; i++)
printf("%s,%d\n", cities[i].name, cities[i].number_of_citizen);
return 0;
}
Could you explain me how to fix this? Why my program only loaded 1 city?
The fscanf() conversion string is incorrect: instead of "%[^,]s %d\n" you should use:
while (i < n && fscanf(fp, "%30[^,],%d",
cities[i].name,
&cities[i].number_of_citizen) == 2) {
i++;
}
Or better:
#include <errno.h>
#include <stdio.h>
#include <string.h>
int load(struct City cities[], int n) {
char buf[200];
int i = 0;
char ch[2];
FILE *fp = fopen("cities.txt", "r");
if (fp == NULL) {
fprintf(stderr, "cannot open %s: %s\n", "cities.txt",
strerror(errno));
return -1;
}
while (i < n && fgets(buf, sizeof buf, fp)) {
if (sscanf(buf, "%30[^,],%d%1[\n]",
cities[i].name,
&cities[i].number_of_citizen, ch) == 3) {
i++;
} else {
fprintf(stderr, "invalid record: %s\n", buf);
}
}
fclose(fp);
return i;
}
Also change your main function to output commas between the city names and population counts:
int main() {
int i, number_of_cities;
struct City cities[10];
FILE *fp = fopen("cities.txt", "w");
if (fp) {
fputs("Sarajevo,345123\n", fp);
fputs("Tuzla,123456\n", fp);
fputs("Mostar,101010\n", fp);
fputs("Banja Luka,234987\n", fp);
fclose(fp);
}
number_of_cities = load(cities, 10);
printf("%d\n", number_of_cities);
for (i = 0; i < number_of_cities; i++)
printf("%s,%d\n", cities[i].name, cities[i].number_of_citizen);
return 0;
}
EDIT: since there are no commas in the database file, you must use a different parsing approach:
#include <errno.h>
#include <stdio.h>
#include <string.h>
int load(struct City cities[], int n) {
char buf[200];
int i = 0;
FILE *fp = fopen("cities.txt", "r");
if (fp == NULL) {
fprintf(stderr, "cannot open %s: %s\n", "cities.txt",
strerror(errno));
return -1;
}
while (i < n && fgets(buf, sizeof buf, fp)) {
/* locate the last space */
char *p = strrchr(buf, ' ');
if (p != NULL) {
/* convert it to a comma */
*p = ',';
/* convert the modified line */
if (sscanf(buf, "%30[^,],%d",
cities[i].name,
&cities[i].number_of_citizen) == 2) {
i++;
continue;
}
}
fprintf(stderr, "invalid record: %s", buf);
}
fclose(fp);
return i;
}

How to print the text from a file if the line number is given?

I want to give input as line number and get output as the corresponding text for that line number in a text file.
Sample text file:
Hi this is Stefen
Hi How are you
Example input:
Enter the line number:2
Expected Output:
Hi How are you
My program is:
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *fp;
fp = fopen("sample.txt", "r");
if (fp == NULL) {
perror("Unable to open the file\n");
exit(1);
}
char buf[256];
while (fgets(buf, sizeof(buf), fp) != NULL) {
printf("%s\n", buf);
print("~~~~\n");
}
fclose(fp);
return 0;
}
Output I got:(The entire file with the separator ~~~~ below each line)
Hi this is Stefen
~~~~
Hi How are you
~~~~
Can anyone please tell me how to do this?
As pmg suggests, would you please try the following:
#include <stdio.h>
#include <stdlib.h>
#define INFILE "sample.txt"
int main()
{
FILE *fp;
char buf[BUFSIZ];
int count = 0, n;
fp = fopen(INFILE, "r");
if (fp == NULL) {
perror(INFILE);
exit(1);
}
printf("Enter the line number: ");
fgets(buf, sizeof buf, stdin);
n = (int)strtol(buf, (char **)NULL, 10);
while (fgets(buf, sizeof buf , fp) != NULL){
if (++count == n) {
printf("%s", buf);
break;
}
}
fclose(fp);
return EXIT_SUCCESS;
}
Best to use a second file
check if you're at \n that means new line and increment a variable like "line"
printf(" \n Enter line number of the line to be deleted:");
scanf("%d", &delete_line);
//open new file in write mode
ptr2 = fopen("c:\\CTEMP\\newfile.txt", "w");
if(ptr2==NULL)
printf("second error opening newfile");
while (!feof(ptr1))
{
ch = fgetc(ptr1);
if (ch == '\n')
{
temp++;
}
//except the line to be deleted
if (temp != delete_line)
{
//copy all lines in file newfile.c
fputc(ch, ptr2);
}
}
fclose(ptr1);
fclose(ptr2);
"detele_line" variable is for the user to inter.
The easiest way is using array to save the lines, then print the certain line.
#include <stdio.h>
#define M 10010
#define N 256
char buf[M][N];
int main(){
FILE *file;
char fileName[50] = "sample.txt";
file = fopen(fileName, "r");
if(file == NULL)
return 1;
int n = 0;
while(fgets(buf[n], N, file) != NULL){
n++;
}
fclose(file);
int i, x;
printf("Example input:\nEnter the line number:");
scanf("%d", &x);
printf("Expected Output:\n%s", buf[x-1]);
return 0;
}

C program to print line number in which given string exists in a text file

I have written a C program that opens a text file and compares the given string with the string present in the file. I'm trying to print the line number in which the same string occurs, but I am unable to get the proper output: output does not print the correct line number.
I would appreciate any help anyone can offer, Thank you!
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
int main() {
int num = 0, line_number = 1;
char string[50];
char student[100] = { 0 }, chr;
while (student[0] != '0') {
FILE *in_file = fopen("student.txt", "r");
if (in_file == NULL) {
printf("Error file missing\n");
exit(1);
}
printf("please enter a word \n");
scanf("%s", student);
while (fscanf(in_file, "%s", string) == 1) {
if (chr == '\n') {
if (strstr(string, student) == 0) {
break;
} else
line_number += 1;
}
}
printf("line number is: %d\n", line_number);
fclose(in_file);
}
return 0;
}
You cannot read lines with while (fscanf(in_file, "%s", string), the newlines will be consumed by fscanf() preventing you from counting them.
Here is an alternative using fgets():
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char string[200];
char student[100];
int num = 0, line_number = 1;
FILE *in_file = fopen("student.txt", "r");
if (in_file == NULL) {
printf("Error file missing\n");
exit(1);
}
printf("please enter a word \n");
if (scanf("%s", student) != 1) {
printf("No input\n");
exit(1);
}
while (fgets(string, sizeof string, in_file)) {
if (strstr(string, student)) {
printf("line number is: %d\n", line_number);
}
if (strchr(string, '\n')) {
line_number += 1;
}
fclose(in_file);
}
return 0;
}

Read numbers from txt file second line in a C Array

I do have a txt file which looks like this
10
41 220 166 29 151 47 170 60 234 49
How can I read only the numbers from the second row into an array in C?
int nr_of_values = 0;
int* myArray = 0;
FILE *file;
file = fopen("hist.txt", "r+");
if (file == NULL)
{
printf("ERROR Opening File!");
exit(1);
}
else {
fscanf(file, "%d", &nr_of_values);
myArray = new int[nr_of_values];
// push values from second row to this array
}
How can I read only the numbers from the second row into an array in C?
Ignore the first line by reading and discarding it.
You could use something like that:
#include <stddef.h>
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
char const *filename = "test.txt";
FILE *input_file = fopen(filename, "r");
if (!input_file) {
fprintf(stderr, "Couldn't open \"%s\" for reading :(\n\n", filename);
return EXIT_FAILURE;
}
int ch; // ignore first line:
while ((ch = fgetc(input_file)) != EOF && ch != '\n');
int value;
int *numbers = NULL;
size_t num_numbers = 0;
while (fscanf(input_file, "%d", &value) == 1) {
int *new_numbers = realloc(numbers, (num_numbers + 1) * sizeof(*new_numbers));
if (!new_numbers) {
fputs("Out of memory :(\n\n", stderr);
free(numbers);
return EXIT_FAILURE;
}
numbers = new_numbers;
numbers[num_numbers++] = value;
}
fclose(input_file);
for (size_t i = 0; i < num_numbers; ++i)
printf("%d ", numbers[i]);
putchar('\n');
free(numbers);
}

Parse a text file into multiple variables with fgets in C

My goal is to create two variables in C from the text file that can be used later in the code. My first variable will be the data from lines 1, 3, 5, 7 and so on. The second variable will be the data from lines 2, 4, 6, and so on.
Main function:
#include <stdio.h>
int main() {
FILE *file;
char buf[500];
file = fopen("ANTdata.txt", "r");
if (!file) {
return 1;
}
while (fgets(buf, 500, file) != NULL) {
printf("%s", buf);
}
fclose(file);
return 0;
}
Example of text file:
0.0002746660
-0.0013733300
-0.0002136290
-0.0002746660
0.0021362900
-0.0006103680
0.0006103680
-0.0022583600
-0.0011291800
-0.0005798500
0.0000000000
-0.0001831100
0.0000915552
-0.0015259200
Your problem can be solved easily with fscanf():
#include <stdio.h>
int main() {
FILE *file;
double x1[1000], x2[1000];
int n;
file = fopen("ANTdata.txt", "r");
if (!file) {
return 1;
}
for (n = 0; n < 1000 && fscanf(file, "%lf%lf", &x1[n], &x2[n]) == 2; n++)
continue;
fclose(file);
/* arrays x1 and x2 have `n` elements, perform your computations */
...
return 0;
}
If you just want to handle 2 lines at a time with a different function, here is a simple solution:
#include <stdio.h>
#include <string.h>
void my_function(const char *line1, const char *line2) {
printf("x: %s, y: %s\n", line1, line2);
}
int main() {
FILE *file;
char line1[250], line2[250];
file = fopen("ANTdata.txt", "r");
if (!file) {
return 1;
}
while (fgets(line1, sizeof line1, file) && fgets(line2, sizeof line2, file)) {
/* strip the trailing newlines if any */
line1[strcspn(line1, "\n")] = '\0';
line2[strcspn(line2, "\n")] = '\0';
my_function(line1, line2);
}
fclose(file);
return 0;
}
Here is a simple anwser (can be improved) :
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char const *argv[])
{
FILE * fp;
fp = fopen("ANTdata.txt", "r");
char * line;
char oddLine[100];
char evenLine[100];
if (fp == NULL)
exit(EXIT_FAILURE);
int i = 0;
int endOfFile = 1;
int res = 0;
size_t len = 0;
while(endOfFile)
{
if(i % 2 == 0){
res = getline(&line, &len, fp);
strcpy(evenLine, line);
printf("even : %s", evenLine);
}else{
res = getline(&line, &len, fp);
strcpy(oddLine, line);
printf("odd : %s", oddLine);
}
if(res == -1)
endOfFile = 0;
i++;
}
fclose(fp);
return 0;
}
The output is :
even : 0.0002746660
odd : -0.0013733300
even : -0.0002136290
odd : -0.0002746660
even : 0.0021362900
odd : -0.0006103680
even : 0.0006103680
odd : -0.0022583600
even : -0.0011291800
odd : -0.0005798500
even : 0.0000000000
odd : -0.0001831100
even : 0.0000915552
odd : -0.0015259200
even : -0.0015259200
You can use strtod to convert a text representation of a floating point value to floating point:
#include <stdlib.h>
...
char *chk;
double x = strtod( buf, &chk );
chk will point to the first character not converted - if that character is not whitespace or a string terminator, then your input was not a valid float constant:
if ( !isspace( *chk ) && *chk != 0 )
{
// bad input, handle as appropriate
}
If you don't want to bother with error checking (you know your input file is good), you can pass NULL as the second argument.
How you handle assigning which input to which variable is up to you. If you want to keep your current loop structure (loop while valid input is read), you'll need a way to keep track of which row you're on, and then decide based on that. Here's one (somewhat fragile) approach:
int xvals[N], yvals[N];
int row = 0, i = 0;
while ( fgets ( buf, sizeof buf, file ) )
{
if ( ++row % 2 ) // row is odd
xvals[i] = strtod( buf, NULL ); // error checking omitted for brevity
else
yvals[i++] = strtod( buf, NULL ); // advance i after both x and y are read
...
}

Resources