Read numbers from text file and use them as input - c

I have this text:
0 0 0 0 0 1
0 0 0 0 1 1
0 0 0 1 0 1
0 0 0 1 1 1
I want to read the first 5 numbers from each line and then use them as inputs in a function.
I'm new to c and have only accomplished this code that doesn't do much, if anything really.
int v,o;
FILE *mydata;
if ((mydata = fopen("testinputs.txt", "rt"))==NULL)
{
printf ("file can't be opened'\n");
exit(1);}
fclose(mydata);
How do i complete it?
Thank you.

Well, assuming your file is called "input.txt", then this is all you need to do:
#include <stdio.h>
#include <stdlib.h>
#define LINE_LEN 100
int main ( void )
{
char line[LINE_LEN];
int sum, i, read_cnt, numbers[5];//sum and i are there for my example usage
FILE *in = fopen("input.txt", "r");//open file
if (in == NULL)
{
fprintf(stderr, "File could not be opened\n");
exit( EXIT_FAILURE);
}
while((fgets(line, LINE_LEN, in)) != NULL)
{//read the line
//scan 5 numbers, sscanf returns the number of values it managed to extract
read_cnt = sscanf(
line,
"%d %d %d %d %d",
&numbers[0],
&numbers[1],
&numbers[2],
&numbers[3],
&numbers[4]
);
//check to see if we got all 5 ints
if (read_cnt != 5)
printf("Warning: only read %d numbers\n", read_cnt);//whoops
//just an example, let's add them all up
for (sum= i=0;i<read_cnt;++i)
sum += numbers[i];
printf("Sum of numbers was: %d\n", sum);
}
return EXIT_SUCCESS;
}
With this input.txt file:
1 2 3 4 5
2 2 2 2 2
1 23 2 3 4
12 23
This gives us the following output:
Sum of numbers was: 15
Sum of numbers was: 10
Sum of numbers was: 33
Warning: only read 2 numbers
Sum of numbers was: 35
That should be more than enough to get you started

Here is a small code to read character by character and store only the wanted numbers:
C Code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int c; // Character read from the file
int cpt; // Counter (to get only 5 numbers per line)
int i,j; // Array indexes
int data[4][5]; // 2D integer array to store the data
FILE *f; // File
if ((f = fopen("file.txt", "r")) == NULL) // Open the file in "read" mode
{
printf ("file can't be opened'\n");
exit(255);
}
// Counter and indexes initialization
cpt=0;
i=0;
j=0;
// Read the file till the EOF (end of file)
while ((c = fgetc(f)) != EOF)
{
// If 5 numbers read, go to new line, first index in the data array and to the next line in the file
if(cpt==5)
{
i++;
cpt=0;
j=0;
while(c != '\n' && c != EOF)
c=fgetc(f);
}
// If a number is read, store it at the right place in the array
if(c>='0'&&c<='9')
{
// Convert character to integer (see ascii table)
data[i][j] = c-'0';
j++;
cpt++;
}
}
// Display the array
for(i=0;i<4;i++)
{
for(j=0;j<5;j++)
printf("%d ", data[i][j]);
printf("\n");
}
fclose(f);
}
And here is the output:
0 0 0 0 0
0 0 0 0 1
0 0 0 1 0
0 0 0 1 1
Now you can use your 2D array, for example if you want a variable a to have the 2nd line, 3rd number, you'd do : a = data[1][2]
Don't forget arrays start at index 0
Hope this helps...

It might help you:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
FILE *datafile;
int main()
{
char line[100],*ch;
int count;
datafile = fopen ( "my.txt", "r");
while ( fgets(line , sizeof line , datafile) != NULL )//fgets reads line by line
{
count = 0;
ch = strtok ( line , " ");
while ( count < 5 && ch != NULL )
{
printf("%d ",*ch - 48 );//*ch gives ascii value
//pass to any function
count++;
ch = strtok ( NULL, " ");
}
}
return 0;
}
The above program passes integer by integer.

Related

How to input stdin strings into array and print them? C Programming

I am practicing how to code C programs, specifically reading stdin statements. The following is a code I wrote to take in the stdin, but I am having trouble inputting them into an array and printing out the correct values.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int main(int argc, char* argv[])
{
int count = 0;
char* number = "-n";
int result;
char numArray[50];
result = strcmp(argv[1], number);
if (result == 0) {
printf("Numbers Only\n");
while (!feof(stdin)) {
if (feof(stdin))
break;
for (int i=0; i < sizeof(numArray); i++){
scanf("%s", &numArray[i]);
}
}
}
for (int i=0; i< sizeof(numArray); i++){
printf("%d\n", numArray[i]);
}
}
I am working step by step, so my final code has something to do with manipulating the array and outputting it. However, my question is focusing solely on inputting the stdin into the array first since that is the big step and I will work on manipulating the array later.
The 'Numbers Only' is what I was using to check something out, so do not worry about that at all.
I do not get any errors for the code, but it gives weird outputs. One output is the following:
1 (1, 2, 3 are what I inputted into terminal)
2
3
49
50
51
0
0
0
0
0
32
-56
109
-63
6
127
0
0
-128
80
110
-63
6
127
0
0
20
0
0
0
0
0
0
0
64
0
0
0
0
0
0
0
0
0
-16
-67
6
127
0
0
4
0
Can anyone explain why it outputs those other numbers when my stdin stops after I input 1 2 3 ctrl+D and how I can stop that from happening? I want my array to be the size of how many numbers I input, but I am also having trouble with that if anyone has hints!
Thanks!
The innermost loop is not necessary, only one loop is enough.
When converting with scanf, check its return value.
Also, only print the number of elements actually converted.
Fixing these, a first corrected version is:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int main(int argc, char* argv[])
{
int count = 0;
char* number = "-n";
int result;
int numArray[50];
int i = 0;
if (argc != 2)
return EXIT_FAILURE;
result = strcmp(argv[1], number);
if (result == 0) {
printf("Numbers Only\n");
while (1) {
int number = 0;
int ret = scanf("%d", &number);
if (ret == 1)
numArray[i++] = number;
if (i == 50 || ret < 1)
break;
}
}
for (int j=0; j< i; j++){
printf("%d\n", numArray[j]);
}
}
Testing:
$ gcc main.c && ./a.out -n
Numbers Only
1
2
3
<CTRL + d here>
1
2
3
Edits from comments: Removed while (!feof(stdin)), expanded error checking to avoid infinite loop and added a check before accessing argv.

In C is their anyway way to read the contents of a file, line-by-line, and store each integer value (preline) into a array separately?

My C Code is as so:
#include <stdio.h>
int main( int argc, char ** argv){
FILE *myFile;
myFile = fopen("numbers.txt", "r");
//read file into array
int numberArray[16];
for (int i = 0; i < 16; i++){
fscanf(myFile, "%1d", &numberArray[i]);
}
for (int i = 0; i < 16; i++){
printf("Number is: %d\n", numberArray[i]);
}
}
My numbers.txt file contains the follow values:
5
6
70
80
50
43
But for some reason my output
Number is: 5
Number is: 6
Number is: 7
Number is: 0
Number is: 8
Number is: 0
Number is: 5
Number is: 0
Number is: 4
Number is: 3
Number is: 0
Number is: 0
Number is: 4195904
Number is: 0
Number is: 4195520
Number is: 0
However I'm expecting it to print out numberArray to print out the identical contents of the text file. I'm not exactly sure why it's doing this, does anyone happen to know the reason? I'm aware that I'm making an array bigger than the amount of values that I can store, but I'm still confused as to why it can't store 70, 80, etc into one index?
It is because you are reading only 1 digit at a time.
Hence change the below.
fscanf(myFile, "%1d", &numberArray[i]);
to
fscanf(myFile, "%d", &numberArray[i]);
And your array should be of size number of integers in the file.
int numberArray[6];
for (int i = 0; i < 6; i++)
or
while (fscanf(myFile, "%d", &numberArray[i++]) == 1);
#include <stdio.h>
#include <stdlib.h>
int main(void) {
FILE *myFile = fopen("numbers.txt", "r"); // just init your variable directly
if (!myFile) { // Always check if there is no error
return EXIT_FAILURE; // handle it as you like
}
#define SIZE 16 // Avoid magic number
int numberArray[SIZE];
size_t n = 0; // n will represent the size of valid values inside the array
// Always check if scanf family has parsed your input also "%1d" ask to only parse
// one digit, so use %d if you want parse an integer
while (n < SIZE && fscanf(myFile, "%d", numberArray + n) == 1) {
n++;
}
for (size_t i = 0; i < n; i++) {
printf("Number is: %d\n", numberArray[i]);
}
}

how to get the number of integer in a file with empty space in it

number.txt
1 2 3 4 5 6 7 8 9 10 11 12 13 14
For instance, I have the above text file. I would like to get the number of integer in the file (which is 14 in this case), and pass every integer into an array.
what I did is
int count = 0;
int i = 0;
while ( 1 )
{
int c = fgetc( fp );
if ( c == EOF || c == '\n' )
{
if ( c == EOF ) break;
}
else if(c ==' ')
{
++count;
--count;
}
else
{
++count;
arr[i] = c-48; // This line give me the wrong number so I subtract it by 48
++i;
}
}
In the case, the count will only get the correct value when there is no double digits number in the file(such as 10 11 12 13). Otherwise, it does not work.
I also tried to use fscanf to store every integer in an array, then get the length of the array. That does not work since I have to define the length of the array first and there is no way I can do that.
My question is how to deal with the double digits number in the file in order to get the right value. Is there a better to do that? Can someone help? Thanks in advance.
You can just read the integers with fscanf(), and every time a number is found, increment a counter.
Something as simple as this could work:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
FILE *fp;
int num;
size_t count = 0;
fp = fopen("somenumbers.txt", "r");
if (!fp) {
fprintf(stderr, "Error reading file\n");
return 1;
}
while (fscanf(fp, "%d", &num) == 1) {
count++;
}
printf("number of digits = %zu\n", count);
fclose(fp);
return 0;
}

Strok spaces using buffer/dynamic memory

how could I strtok at spaces while reading in data from a buffer? If my text file contained
1 23 50
45 50 30
2 15 30
and I decide to print the array with my code below, it will print line by line. How could I extend this to further divide the array into individual numbers for each index of the array? Eg.
1
23
50, etc...
I've tried playing around with strtok but I keep segfaulting and I wasn't sure where to fix it.
FILE * fp;
char buffer[5000];
int size = 0;
char **entireFile = NULL;
fp = fopen("file.txt","r");
entireFile = malloc(sizeof(buffer) * sizeof(char*));
while (fgets(buffer,5000,fp)!= NULL)
{
entireFile[size] = malloc(strlen(buffer)+1);
strcpy(entireFile[size],buffer);
size++;
}
I want entireFile[0] = 1, entireFile1 = 23
This can easily be accomplished with fscanf. Here is a pretty good reference for scanning in inputs.
#include <stdio.h>
int main(){
FILE *in = fopen("in.txt" , "r");
int hold;
/* Won't actually store values, but can be used for
value manipulation inbetween */
while ( fscanf(in, "%d", &hold) != EOF ){
printf("Scanned in %d\n", hold);
}
fclose(in);
return 0;
}
If you want this in an array form, add an incrementing integer and change the hold to an array.
#include <stdio.h>
int main(){
FILE *in = fopen("in.txt" , "r");
int hold[100], i=0; // Hold a maximum of 100 integers
while ( fscanf(in, "%d", &hold[i]) != EOF ){
printf("Scanned in %d\n", hold[i++]);
}
fclose(in);
return 0;
}
You could also do dynamic memory allocation like this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
FILE *in = fopen("in.txt", "r");
int i=0, j;
char* fragments[2000];
char entry[100];
while ( fscanf(in, "%s", &entry[i]) != EOF ){
fragments[i] = malloc(sizeof(char) * (1 + strlen(entry)));
strcpy(fragments[i], &entry[i]);
i++;
}
for ( j = 0; j < i; j++ ){
printf("%s\n", fragments[j]);
}
fclose(in);
return 0;
}
This will read 1, 2, or 3 numbers on each line of your file. It uses the return value from sscanf to see how many numbers were read from each line. Of course, if there is any rogue non-numerical data, it will mess up.
#include <stdio.h>
int main(void)
{
FILE *fp;
int a, b, c;
int res;
char str [100];
if ((fp = fopen("file.txt", "rt")) == NULL)
return 1;
while(fgets(str, sizeof str, fp) != NULL) {
res = sscanf(str, "%d%d%d", &a, &b, &c);
if (res == 3)
printf ("3 values %d %d %d\n", a, b, c);
else if (res == 2)
printf ("2 values %d %d\n", a, b);
else if (res == 1)
printf ("1 value %d\n", a);
else
printf ("0 values\n");
}
fclose(fp);
return 0;
}
File content:
1 23 50
45 50 30
2 15 30
10 20
100
Program output:
3 values 1 23 50
3 values 45 50 30
3 values 2 15 30
2 values 10 20
0 values
1 value 100

Jump to next line in .txt file in C

I need to make some actions from txt file.
What I was willing to do:
Calculate number of lines in txt
Open txt file
Iterate for each line
Iterate within each line and perform the task within it
Close file
Current code:
int lines(){
FILE *fp = fopen("somedata.txt","r");
int ch;
int count=0;
do{
ch = fgetc(fp);
if( ch== '\n') count++;
}
while( ch != EOF );
fclose(fp);
return count;
}
int main(){
int linesnum=lines();
FILE *fp = fopen("somedata.txt", "r");
if (fp == 0){
fprintf(stderr, "failed to open test0.txt\n");
exit(-1);
}
float areas[linesnum];
for (int j=0;j<linesnum;j++){
float array[150];
for (int i = 0; i < 150; i++){
fscanf(fp, "%f", &array[i]);
if (getc(fp) == (int)'\n'){
//that ends iteration for a line once it founds "\n"
//and assigns its value to temporary array
break;
}
}
//SOME TASK PERFORMED OVER HERE FOR EACH LINE lets say calculate average
if (getc(fp) == EOF){ //That's supposed to be end of iteration through lines
break;
}
}
fclose(fp);
return 0;
}
File is in format (max lines 1000, max elements in each line is 150).
Number of elements in each line is different, so if I make a big matrix of 1000x150, most of elements will be empty; that's why I don't want a matrix, and just simply want perform task for each line.
1 2 3 4 5 6
1 3 2 5 6 7 3 5
1 3 3 2 5 2 3
5 3 4 2 52 5 6
Well, I'm ending up with error Segmentation fault: 11 after performing task for 1st line.
I'm not sure how do I jump to next line after 1st iteration. That's the question.
Any thoughts?
UPDATE: Just had to get rid of EOF break thing in main():
if (getc(fp) == EOF){
break;
}
Something like this may work.
Read a line with fgets. The line must be large enough to hold the longest line.
Use a pointer to line and an offset to parse the values from the line.
%n will receive the number of bytes used by the sscanf so the pointer can be advanced to the next value.
char line[1500];
char *pline;
int used = 0;
int i = 0;
int linesnum = 0;
float array[150];
while ( fgets ( line, sizeof ( line), fp))) {
pline = line;
i = 0;
while ( ( sscanf ( pline, "%f%n", &array[i], &used)) == 1) {
pline += used;
i++;
if ( i >= 150) {
break;
}
}
linesnum++;
if ( linesnum >= 1000) {
break;
}
}

Resources