Read int values from a text file in C - c

I have a text file that contains the following three lines:
12 5 6
4 2
7 9
I can use the fscanf function to read the first 3 values and store them in 3 variables. But I can't read the rest.
I tried using the fseek function, but it works only on binary files.
Please help me store all the values in integer variables.

A simple solution using fscanf:
void read_ints (const char* file_name)
{
FILE* file = fopen (file_name, "r");
int i = 0;
fscanf (file, "%d", &i);
while (!feof (file))
{
printf ("%d ", i);
fscanf (file, "%d", &i);
}
fclose (file);
}

How about this?
fscanf(file,"%d %d %d %d %d %d %d",&line1_1,&line1_2, &line1_3, &line2_1, &line2_2, &line3_1, &line3_2);
In this case spaces in fscanf match multiple occurrences of any whitespace until the next token in found.

Related

How to to properly use the fopen command in C?

I'm trying to create a program that asks a user to input the file name they wish to open and then using it to open the file as per user input.
Below is what I have so far. (Keep in mind that this is intro to C language):
#include <stdio.h>
int
main (void)
{
FILE *data_File;
char fileName[6];
int ecoli_lvl;
printf ("Which month would you like a summary of? \nType month followed by date (i.e: july05): ");
scanf ("%lf", &fileName);
data_File = fopen (fileName, "r");
fscanf (data_File, "%d", &ecoli_lvl);
printf ("%d", ecoli_lvl);
return (0);
}
The data in the text file is all integers as below:
1 101 5 66.6 33.3 22.2 98.9 11.1
5 501 2 33.3 44.3
And yet what the program prints is dependent on the number I put in the square brackets for char fileName[x] (I thought the x signifies that length in characters for what the user will input. How to I code the above properly so that it prints all the numbers I have in the file?
Thanks a lot for all the help.
Errors to fix:
Size of the array for file name.
char fileName[6];
This can hold a file name that is at most 5 characters long. Make the array size bigger.
char fileName[200]; // Hopefully that is sufficient.
Reading the name of the file.
scanf ("%lf", &fileName);
%lf is the wrong format to use for reading strings. Also, you don't need &fileName. Just fileName is the right thing to use.
scanf ("%199s", fileName); // Make sure that format also
// specifies the maximum number
// of characters that should be read
// in to fileName.
Check the return value of fopen before using it.
data_File = fopen (fileName, "r");
if ( data_File != NULL )
{
fscanf (data_File, "%d", &ecoli_lvl);
}
Your data looks like floating point inputs to me:
#include <stdio.h>
int main()
{
FILE *data_File;
char fileName[256] = { 0 };
double ecoli_lvl;
while (1)
{
printf("Of which month would you like a summary?\nType month followed by date (i.e: july05): ");
fflush(stdout);
scanf("%255s", fileName);
if (NULL != (data_File = fopen(fileName, "r")))
break;
perror("Couldn't open file!");
}
while (1 == fscanf(data_File, "%lf", &ecoli_lvl))
printf("%lf ", ecoli_lvl);
printf("\n");
fclose(data_File);
return (0);
}

Segmentation fault solution

I have a text file having info as
Emp_Id Dept_Id
1 1
1 2
1 3
2 2
2 4
I am trying to read this file through C with this code below :
#include "stdio.h"
#include "stdlib.h"
int main()
{
FILE *fp;
char line[100];
char fname[] = "emp_dept_Id.txt";
int emp_id, dept_id;
// Read the file in read mode
fp = fopen(fname, "r");
// check if file does not exist
if (fp == NULL)
{
printf("File does not exist");
exit(-1);
}
while (fgets(line, 100, fp) != NULL)
{
printf("%s", line);
sscanf(line, "%s %s", &emp_id, &dept_id);
printf("%s %s", dept_id, dept_id);
}
fclose(fp);
return 0;
}
While i am trying to compile the code its all fine but when running it shows the follwoing error :
Segmentation fault (core dumped)
What can be the possible solution and mistakes for my code .
thanks
P.S : I am on IBM AIX and using CC . And have no other option to move from them .
Use %d to scan and print integers:
sscanf(line, "%d %d", &emp_id, &dept_id);
printf("%d %d", dept_id,dept_id);
(You should probably be checking the return value of sscanf as well, to make sure it really did read two integers - reading the first line into integers isn't going to work.)
You are trying to scan and print two integers using %s, it should be %d.
Your code invokes undefined behaviour because you use the wrong conversion specifier for reading and printing integers. You should use %d instead of %s. Also, output a newline to immediately print output to the screen as stdin stream is line buffered by default. Change your while loop to
while(fgets(line, 100, fp) != NULL)
{
// output a newline to immediately print the output
printf("%s\n", line);
// change %s to %d. also space is not needed
// between %d and %d since %d skips the leading
// whitespace characters
sscanf(line, "%d%d", &emp_id, &dept_id);
// sscanf returns the number of input items
// successfully matched and assigned. you should
// check this value in case the data in the file
// is not in the correct format
// output a newline to immediately print the output
printf("%d %d\n", dept_id, dept_id);
}

Read a line and convert to string in c

This is my first post here so dont really know how to post something here with correct format. I have a question on how to read a line from file and read some of the words as string and some as Int.
int check = sscanf(read, "%s %d", string, &integer);
printf("%s, %d", string, integer);
Above is kind of what I did. The input is "oneword 1". What I got is "(null) 4196448". So how can I do it correctly? Thank you
Here is part of my code.
int i;
for (i = 1; i <= 3; i++)
{
char read[MAX_LENGTH_INPUT];
fgets(read, sizeof(read), stdin);
int check2 = sscanf(read, "%s %d", word, &number);
printf("%s %d\n", word, number);
}
So the for loop is to scan three lines in .in file. Can I do that?
Here is the .in file which is the input.
oneword 1
twoword 2
thirdword 3
The output was
(null) 4196448
(null) 4196448
(null) 4196448
Also in your code int check2 = sscanf(read, "%s %d %d", word, &number); format specifier are 3 but arguments 2.
if file contain data like
oneword 1
secondword 2
thirdword 3
fourthword 4
Then
#include <stdio.h>
int main ()
{
FILE *fp = fopen("file", "r");
char read[100];
int integer;
char string[64];
while (fgets(read, sizeof(read), fp) != NULL)
{
int check = sscanf(read, "%s %d", string, &integer);
if (check == 2) {
printf("%s, %d\n", string, integer);
}
else{
printf("Failed to scan all values\n");
}
}
}
And output is
oneword, 1
secondword, 2
thirdword, 3
fourthword, 4
You can modify fgets here to take input from stdin by just replacing fp by stdin in line while (fgets(read, sizeof(read), fp) != NULL)
You are using sscanf
which reads data from char * type and stores them according to parameter format into the locations given by the additional arguments, as if scanf was used, but reading from string instead of the standard input (stdin).
you need to use fscanf and read in your code should be pointer to a FILE.

Using fscanf to check if more lines exist

I have this function to read numbers from txt files that are structured like so:
1 2 5
2 1 9
3 5 8
The function reads the values correctly into my values, but I want to check if the line I have read is the last in the file.
My last if statement in the below function attempts to do this by seeing if fscanf produces NULL but it doesn't work, the function always returns NULL even if it's not the last line.
void process(int lineNum, char *fullName)
{
int ii, num1, num2, num3;
FILE* f;
f = fopen(fullName, "r");
if(f==NULL)
{
printf("Error: could not open %S", fullName);
}
else
{
for (ii=0 (ii = 0; ii < (lineNum-1); ii++)
{
/*move through lines without scanning*/
fscanf(f, "%d %d %d", &num1, &num2, &num3);
}
if (fscanf(f, "%*d %*d %*d\n")==NULL)
{
printf("No more lines");
}
fclose(f);
}
}
Check this below code.Using this code u can see whether you have reached the end of file or not.It is not suggested to use fscanf to read the end of file.
/* feof example: byte counter */
#include <stdio.h>
int main ()
{
FILE * pFile;
int n = 0;
pFile = fopen ("myfile.txt","r");
if (pFile==NULL) perror ("Error opening file");
else
{
while (fgetc(pFile) != EOF) {
++n;
}
if (feof(pFile)) {
puts ("End-of-File reached.");
printf ("Total number of bytes read: %d\n", n);
}
else puts ("End-of-File was not reached.");
fclose (pFile);
}
return 0;
}
You can use feof() to check if you are reading past the end of the file.
From man page of fscanf:
RETURN VALUE
These functions return the number of input items successfully matched
and assigned, which can be fewer than provided for, or even zero in the
event of an early matching failure.
You if the last line that you are trying to read is not in the expected format, fscanf may not read anything and return 0 which is same as NULL.

comparing numbers from two files in c; using fopen etc

I am trying to open two files from inside the code, but I am having trouble trying to get my three numbers from first.txt but it only prints the first one. I just need help printing all the numbers from my text file so no need to finish my whole program but advice is welcomed :)!
int main(int argc, char **argv)
{
int *number1Pointer = malloc(80 * sizeof(int));
FILE *file1;
//FILE *file2;
file1 = fopen("first.txt", "r");
//file2 = fopen("second.txt", "r");
int read = fscanf(file1, "%d", number1Pointer);
if(read != '\0')
{
printf("%d", &number1Pointer);
}
else
{
fclose(file1);
}
return 0;
}
int read = fscanf(file1, "%d", number1Pointer); will just read one "%d" like scanf("%d", &num) from stdin.
You can either use a while loop or fscanf(file1, "%d%d%d", ...).
If you need to read 3 numbers, then you could try with this code
int read = fscanf(file1, "%d %d %d", &number1Pointer[0], &number1Pointer[1], &number1Pointer[2]);
The variable read will have the number of elements read or EOF. Hence, the check will have to be adapted.
If your file contains three numbers separated by a space - i.e. 21 32 32 - you need a format string matching that format:
fscanf(file1, "%d %d %d", &number1Pointer[0], &numberPointer[1], &numberPointer[2]);
Remember to free() your allocated variable after using it.

Resources