Getting only the first number of each line in a file [duplicate] - c

This question already has answers here:
C read file line by line
(17 answers)
Closed 2 years ago.
120 test 123
101 test1 132
126 test2 140
150 test3 150
This is inside of a txt file. What i want to do is getting only the first number in the first line of the file and put it into an array and go to the next line then do the same thing again... for example array[0]={120} , array[1]={101}...
int j,i=1,array[20];
FILE *fp;
fp=fopen("input.txt","r");
for(i=0;i<10;i++)
fscanf(fp,"%d",&array[i]);
This is what i tried to do but i guess fscanf doesnt skip the line after getting the number... It might be a newbie question but i am stuck on that part :P

Continuing from the comment, you want to consume an entire line of input with each read, then parse the first integer from the line into your array. Using fgets() to read each line into a buffer and then parse with sscanf is a simple solution, e.g.
#include <stdio.h>
#define MAXC 1024 /* if you need a constant, #define one (or more) */
#define MAXI 256
int main (int argc, char **argv) {
char buf[MAXC];
int array[MAXI], n = 0;
/* use filename provided as 1st argument (stdin by default) */
FILE *fp = argc > 1 ? fopen (argv[1], "r") : stdin;
if (!fp) { /* validate file open for reading */
perror ("file open failed");
return 1;
}
while (n < MAXI && fgets (buf, MAXC, fp)) /* read each line into buf */
if (sscanf (buf, "%d", &array[n]) == 1) /* parse 1st int from buf to array */
n++; /* increment counter */
if (fp != stdin) /* close file if not stdin */
fclose (fp);
for (int i = 0; i < n; i++)
printf ("array[%2d] : %d\n", i, array[i]);
}
Example Input File
$ cat dat/arr_1st_num.txt
120 test 123
101 test1 132
126 test2 140
150 test3 150
(note: blank lines or lines not beginning with an integer value are simply read and discarded and do not impact your read and storage of data)
Example Use/Output
$ ./bin/array_1st_num dat/arr_1st_num.txt
array[ 0] : 120
array[ 1] : 101
array[ 2] : 126
array[ 3] : 150
Look things over and let me know if you have further questions.

What you can do is you can scan the whole line instead as a string, then you get the first token (which is the first number) by getting the first "token" of the string using the strtok function. Lastly, we use the atoi function to convert the string number to an integer number (don't forget to include stdlib.h)
#include<stdlib.h>
int j, i=1, array[20];
FILE *fp;
fp = fopen("input.txt","r");
char currentLine[1000];
for(i=0; i<10; i++) {
fscanf(fp, "%[^\n]", currentLine);
// extract the first token
char * firstToken = strtok(currentLine, " ");
// store the firstToken (which is the number)
// to the array
array[i] = atoi(firstToken);
}

Related

Reading a text file to extract coordinates in c

i am trying to read a text file and extract the cordinates of 'X' so that i can place then on a map
the text file is
10 20
9 8 X
2 3 P
4 5 G
5 6 X
7 8 X
12 13 X
14 15 X
I tried multiple times but I am unable to extract the relevant data and place it in separate variables to plot
I am quite new to c and am trying to learn things so any help is appreciated
thanks in advance
From my top comments, I suggested an array of point structs.
Here is your code refactored to do that.
I changed the scanf to use %s instead of %c for the point name. It generalizes the point name and [probably] works better with the input line because [I think] the %c would not match up correctly.
It compiles but is untested:
#include <stdio.h>
#include <stdlib.h>
struct point {
int x;
int y;
char name[8];
};
struct point *points;
int count;
int map_row;
int map_col;
void
read_data(const char *file_name)
{
FILE *fp = fopen(file_name, "r");
if (fp == NULL) {
/* if the file opened is empty or has any issues, then show the error */
perror("File Error");
return;
}
/* get the dimensions from the file */
fscanf(fp, "%d %d", &map_row, &map_col);
map_row = map_row + 2;
map_col = map_col + 2;
while (1) {
// enlarge dynamic array
++count;
points = realloc(points,sizeof(*points) * count);
// point to place to store data
struct point *cur = &points[count - 1];
if (fscanf(fp, "%d %d %s", &cur->x, &cur->y, cur->name) != 3)
break;
}
// trim to amount used
--count;
points = realloc(points,sizeof(*points) * count);
fclose(fp);
}
There are a number of way to approach this. Craig has some very good points on the convenience of using a struct to coordinate data of different types. This approach reads with fgets() and parses the data you need with sscanf(). The benefit eliminates the risk of a matching-failure leaving characters unread in your input stream that will corrupt the remainder of your read from the point of matching-failure forward. Reading with fgets() you consume a line of input at a time, and that read is independent of the parsing of values with sscanf().
Putting it altogether and allowing the filename to be provided by the first argument to the program (or reading from stdin by default if no argument is provided), you can do:
#include <stdio.h>
#define MAXC 1024 /* if you need a constand, #define one (or more) */
int main (int argc, char **argv) {
char buf[MAXC]; /* buffer to hold each line */
int map_row, map_col; /* map row/col variables */
/* use filename provided as 1st argument (stdin if none provided) */
FILE *fp = argc > 1 ? fopen (argv[1], "r") : stdin;
if (!fp) { /* validate file open for reading */
perror ("file open");
return 1;
}
/* read/validate first line saving into map_row, map_col */
if (!fgets (buf, MAXC, fp) ||
sscanf (buf, "%d %d", &map_row, &map_col) != 2) {
fputs ("error: EOF or invalid map row/col data.\n", stderr);
return 1;
}
/* loop reading remaining lines, for used as line counter */
for (size_t i = 2; fgets (buf, MAXC, fp); i++) {
char suffix;
int x, y;
/* validate parsing x, y, suffix from buf */
if (sscanf (buf, "%d %d %c", &x, &y, &suffix) != 3) {
fprintf (stderr, "error: invalid format line %zu.\n", i);
continue;
}
if (suffix == 'X') { /* check if line suffix is 'X' */
printf ("%2d %2d %c\n", x, y, suffix);
}
}
if (fp != stdin) { /* close file if not stdin */
fclose (fp);
}
}
(note: this just illustrates the read and isolation of the values from lines with a suffix of 'X'. Data handling, and calculations are left to you)
Example Use/Output
With your data in dat/coordinates.txt you could do:
$ ./bin/readcoordinates dat/coordinates.txt
9 8 X
5 6 X
7 8 X
12 13 X
14 15 X
As Craig indicates, if you need to store your matching data, then an array of struct provides a great solution.

Read Text File with blank lines

The Text File was writable with 1 blank line after the struct.
Is similar to:
1 111 1 Peter
22 22 2 John Lays
3 3 3 Anne Belgs
The struct is:
struct estruturaCarro {
int id, potencia, avariado;
char name[11];
} carro;
I have write the data to the text File:
fprintf(fp, "%-2d %-3d %-1d %-10s \n\n", carro.id, carro.potencia, carro.avariado, carro.name);
I read the file data this way, but I'm sure it's not the best way:
while(true){
int result = fscanf(fp, "%d %d %d %10[^\n]", &carro.id, &carro.potencia, &carro.avariado, &carro.name);
if(result==4){
printf("%-2d %-3d %-1d % -s\n", carro.id, carro.potencia, carro.avariado, carro.name);
}else break;
}
How can I read the text file, saving the data struct, without reading the blank lines?
If I want to validate the values ​​read (ID = xx, potencia = xxx, avariado = x, name = 10 characters), is it better, before or after filling the array of struct?The format of each line of the file is:xx xxx x aaaaaaaaaa (x = digits, a = characters)For example, if one of the lines is
9 123 4 Error 1st value
stop reading the file (informing the user), because the line should be:
9 123 4 Error 1st value (one space was missing after 9) - or because NAME has more than 10 characters.
You don't show how true is set in while(true), but it must be based on the return of fscanf in the way you are approaching it. You must test three cases:
fscanf return is EOF, read done, true should be set to FALSE to break loop;
fscanf return less than 4, matching or input failure, no guarantee this occurred due to an empty line; and
fscanf return is equal to 4, good input.
Unless you are checking all three, you cannot cover all cases for fscanf and further, if there is any additional or extraneous character in your input file, your formatted read will fail.
That is why a better option is to read each line into a buffer with fgets and then parse the information you need from the buffer itself with sscanf. This provides the benefit of allowing separate validation of (1) the read; and (2) the parse of information. Further, since you are consuming a line-at-a-time, there is no uncertainty on what remains in the input stream and a failure in parsing any one line does not prevent a successful read of the remainder.
A short implementation with fgets() and sscanf() reading each struct into an array-of-struct, you can do something similar to the following:
#include <stdio.h>
#define MAXN 11 /* if you need a constant, #define one (or more) */
#define MAXC 1024 /* (don't skimp on buffer size) */
typedef struct { /* use a simple typedef */
int id, potencia, avariado;
char name[MAXN];
} carro_t;
int main (int argc, char **argv) {
char buf[MAXC]; /* buffer to read line */
carro_t carro[MAXN] = {{ .id = 0 }}; /* array of struct */
size_t ndx = 0; /* array index */
/* use filename provided as 1st argument (stdin by default) */
FILE *fp = argc > 1 ? fopen (argv[1], "r") : stdin;
if (!fp) { /* validate file open for reading */
perror ("file open failed");
return 1;
}
while (ndx < MAXN && fgets (buf, MAXC, fp)) { /* read each line */
carro_t tmp = { .id = 0 }; /* temp struct */
if (*buf == '\n') /* if line empty */
continue; /* get next line */
if (sscanf (buf, "%d %d %d %10[^\n]", /* separate/validate */
&tmp.id, &tmp.potencia, &tmp.avariado, tmp.name) == 4)
carro[ndx++] = tmp; /* add to array of struct */
}
if (fp != stdin) fclose (fp); /* close file if not stdin */
for (size_t i = 0; i < ndx; i++)
printf ("%3d %3d %3d %s\n",
carro[i].id, carro[i].potencia, carro[i].avariado, carro[i].name);
return 0;
}
(note: the filename is provide as the first argument to the program, or if no filename is provided, read from stdin by default)
While with your particular data file, there is no reason you cannot use fscanf, it is fragile and one character too many (like "Anne Belgss") will cause it to break. A fscanf implementation removing the true and simply looping as you have could be:
for (;;) {
carro_t tmp = { .id = 0 };
if (fscanf (fp, "%d %d %d %10[^\n]", /* separate/validate */
&tmp.id, &tmp.potencia, &tmp.avariado, tmp.name) == 4)
carro[ndx++] = tmp; /* add to array of struct */
else
break;
}
Either way, you will produce the same output with "this" input file, e.g.
Example Use/Output
$ ./bin/readwblanks ~/tmpd/file
1 111 1 Peter
22 22 2 John Lays
3 3 3 Anne Belgs
just use simple reading way is ok,like this.
while(fscanf(fp,"%d %d %d %s",&carro.id,&carro.potencia,&carro.avariado,carro.name)!=EOF)
printf("%d %d %d %s\n",carro.id,carro.potencia,carro.avariado,carro.name);
result is like this
enter image description here

How to read in 3 input values from a file and read them sequentially?

I'm trying to read three 3 values from a text file (in.txt) that are from the first line. How am I able to implement this in C?
The first line of the text file has 3 numbers (N, S, D). And they represent the sequence of input words in the file. So for example my in.txt file would be:
8 3 5
mary
tom
jane
joe
dave
judy
fred
bill
jane
jones
judy
mary
judy
fred
joe
dave
So the first 8 will correspond to N, following 3 to S, and the last 5 to D. The purpose for this is for me to add the first 8 into a Binary Search Tree, then following 3 to Search in the BST, and the last 5 to delete from the BST.
But for this all I want to know is how I'm able to read them from a file in order to start my BST.
I haven't gotten very far I've only been able to open the file but had to delete other codes due to it not working at all. So this is all I have right now.
int main()
{
FILE *inFile, *outFile;
int n, s, d;
inFile = fopen("in.txt", "r");
while(!feof (inFile))
{
fscanf(inFile, "%d %d %d", &n, &s, &d);
}
fclose(inFile);
}
This is my first post here on Stackoverflow, any help is greatly appreciated!
To begin with, you will want to review Why is while ( !feof (file) ) always wrong?
When reading lines of data from a file, use a line-oriented input function such as fgets() or POSIX getline() to read an entire line into a buffer -- then parse the needed values from the buffer. This provides two primary benefits:
you can independently validate:
a. the read of data from the file; and
b. parsing of the values from the line.
what remains in your input buffer does not depend on the scanf format-specifier used. (an entire line is always consumed, so you are always ready to read from the beginning of the next line for your next input)
Any time you are reading from a file, simply provide a buffer of sufficient size when using fgets (don't skimp on buffer size!). POSIX getline will automatically allocate whatever space is required. Then use sscanf to parse any information needed from the line (or strtok or strsep or any of the other functions you like to locate a specific point within the buffer).
If you are not parsing information and need the whole line, simply trim the '\n' from the end of the buffer by overwriting it with the nul-character. strcspn provides a simple method, or use strlen to get the length then overwrite the last character.
In your case you simply need to handle the first line differently from the remaining lines -- so keep a line-counter initialized to zero at the beginning. If your line counter is zero, then parse 3-integer values from the line, otherwise do whatever you need with the subsequent lines (below they are simply output with along with the line number)
Putting it altogether, you could do something similar to:
#include <stdio.h>
#include <string.h>
#define MAXC 1024 /* don't skimp on buffer size */
int main (int argc, char **argv) {
char buf[MAXC]; /* buffer to hold each line */
int n, s, d; /* your int variables */
size_t ndx = 0; /* line counter */
/* use filename provided as 1st argument (stdin by default) */
FILE *fp = argc > 1 ? fopen (argv[1], "r") : stdin;
if (!fp) { /* validate file open for reading */
perror ("file open failed");
return 1;
}
while (fgets (buf, MAXC, fp)) { /* read each line into buf */
if (!ndx) { /* if 1st line, parse into n, s, d */
if (sscanf (buf, "%d %d %d", &n, &s, &d) == 3)
printf ("line[%2zu] - n: %d s: %d d: %d\n",
ndx + 1, n, s, d);
else { /* if parse fails - handle error */
fputs ("error: invalid format - line 1.\n", stderr);
return 1;
}
}
else { /* for all subsequent lines */
buf[strcspn(buf, "\r\n")] = 0; /* trim '\n' from buf */
printf ("line[%2zu] : %s\n", ndx + 1, buf);
}
ndx++; /* increment line counter */
}
if (fp != stdin) fclose (fp); /* close file if not stdin */
return 0;
}
Example Use/Output
Using your input file, you would get the following:
$ ./bin/rdline1_3int dat/line1_3int.txt
line[ 1] - n: 8 s: 3 d: 5
line[ 2] : mary
line[ 3] : tom
line[ 4] : jane
line[ 5] : joe
line[ 6] : dave
line[ 7] : judy
line[ 8] : fred
line[ 9] : bill
line[10] : jane
line[11] : jones
line[12] : judy
line[13] : mary
line[14] : judy
line[15] : fred
line[16] : joe
line[17] : dave
I would do a thing like this:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
void main()
{
int fd, N, S, D;
char buff[1];
fd = open("in.txt", O_RDONLY);
//reading N
if(read(fd, buff, 1) == -1){
perror("Unable to read N");
exit(0);
}
//converting N to int value
//EDIT
N = atoi(buff);
//skipping the file descriptor to avoid reading the space
lseek(fd, 1, SEEK_CUR);
//reading S
if(read(fd, buff, 1) == -1){
perror("Unable to read S");
exit(0);
}
//converting S to int value
//EDIT
S = atoi(buff);
//skipping the file descriptor to avoid reading the space
lseek(fd, 1, SEEK_CUR);
//reading D
if(read(fd, buff, 1) == -1){
perror("Unable to read N");
exit(0);
}
//converting D to int value
//EDIT
D = atoi(buff);;
close(fd);
//here your values are initialized
}
I didn't test this code, so it may not work, let me know if its working :)

ASCII characters not getting printed out

I want to read cards from an input file and print out their values.
However when I try to print out characters it prints out '0'.
If I print out the character 'A', then normally the int value 65 is supposed to be printed out since I stored the character 'A' as an Int.
Could anyone help me out?
Thank you in advance.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define max 100
#define MAX_LENGTH 14
int main(){
char *lines = malloc(max*sizeof(char));
char **colour = malloc(max*sizeof(char));
int *value =malloc(max*sizeof(int));
FILE *fp;
fp = fopen("config2.txt", "r");
if(fp == NULL){
printf("Cannot open filelist.txt\n");
return 1;
}
int i= 0;
while (i < max && fgets(lines, MAX_LENGTH, fp) != NULL) {
colour[i] = malloc(MAX_LENGTH);
sscanf(lines, "%s %d", colour[i], &value[i]);
printf("%s\n", colour[i]);
printf("%d\n", value[i]);
i++;
}
return 0;
}
input:
RED A
RED 2
RED 3
RED 4
RED 5
RED 6
RED 7
RED 8
RED 9
RED 10
RED J
RED Q
RED K
Your primary problem handling either 'A' or an integer as the value, stems from the misunderstanding that A can be parsed with sscanf using the "%d" format specifier, it can't. Why? When you attempt to parse 'A' with "%d" a matching failure occurs, no further characters are extracted from the input buffer, and the return for sscanf will be the number of successful conversions that took place prior to the failure.
When you have data of differing types, e.g.
RED A
RED 2
In order to parse the values for A or 2, it will require two different sscanf expressions, which you can easily distinguish simply by checking the return for sscanf. You do this in a conditional and if parsing with "%s %d" fails, you attempt the parse with "%s %c" and validate whether that succeeded.
For instance, say instead of allocating with malloc (you are not reallocating anyway), you simply declare an array of struct to hold the color and value read from each line, e.g.
...
#define MAXCOLR 14
#define MAXLINE 100
#define MAXCHR 1024 /* don't skimp on read buffer size */
typedef struct { /* simple struct to associate each color/value */
char color[MAXCOLR];
int value;
} colorval_t;
int main (int argc, char **argv) {
size_t ndx = 0; /* index */
char buf[MAXCHR]; /* read buffer */
colorval_t arr[MAXLINE] = {{ .color = "" }}; /* array of struct */
/* use filename provided as 1st argument (stdin by default) */
FILE *fp = argc > 1 ? fopen (argv[1], "r") : stdin;
...
while (ndx < MAXLINE && fgets (buf, MAXCHR, fp)) {
char c; /* temp char to use for parsing 2nd case */
if (sscanf (buf, "%13s %d", arr[ndx].color, &arr[ndx].value) == 2)
ndx++;
else if (sscanf (buf, "%13s %c", arr[ndx].color, &c) == 2) {
arr[ndx].value = c;
ndx++;
}
}
The while loop above being the operative code for handling the parse of information read from each line into buf. The first sscanf call attempts the parse into a string and integer value. If the return is not 2, then a second call to sscanf is made to attempt to parse the contents into a string and a character. If that succeeds, the character value (e.g. the ASCII value for the character) is assigned to value, which from your question appears to be what you intended.
Adding a few validations and then outputting the color and value for each struct contained in arr, you could do something like the following. (note: the program takes the filename to read as the first argument or reads from stdin by default if no argument is given. Don't hardcode filenames. Either pass the filename as an argument or prompt for its entry)
#include <stdio.h>
#define MAXCOLR 14
#define MAXLINE 100
#define MAXCHR 1024 /* don't skimp on read buffer size */
typedef struct {
char color[MAXCOLR];
int value;
} colorval_t;
int main (int argc, char **argv) {
size_t ndx = 0;
char buf[MAXCHR];
colorval_t arr[MAXLINE] = {{ .color = "" }};
/* use filename provided as 1st argument (stdin by default) */
FILE *fp = argc > 1 ? fopen (argv[1], "r") : stdin;
if (!fp) { /* validate file open for reading */
perror ("file open failed");
return 1;
}
while (ndx < MAXLINE && fgets (buf, MAXCHR, fp)) {
char c;
if (sscanf (buf, "%13s %d", arr[ndx].color, &arr[ndx].value) == 2)
ndx++;
else if (sscanf (buf, "%13s %c", arr[ndx].color, &c) == 2) {
arr[ndx].value = c;
ndx++;
}
}
if (fp != stdin) fclose (fp); /* close file if not stdin */
for (size_t i = 0; i < ndx; i++)
printf ("arr[%2zu] : %-14s %d\n", i, arr[i].color, arr[i].value);
return 0;
}
(note: the use of the field-width modifier 13 to protect the character array bounds for color)
Example Use/Output
Using your data as input would result in the following:
$ ./bin/rdcolorval <dat/colorval.txt
arr[ 0] : RED 65
arr[ 1] : RED 2
arr[ 2] : RED 3
arr[ 3] : RED 4
arr[ 4] : RED 5
arr[ 5] : RED 6
arr[ 6] : RED 7
arr[ 7] : RED 8
arr[ 8] : RED 9
arr[ 9] : RED 10
arr[10] : RED 74
arr[11] : RED 81
arr[12] : RED 75
Look things over and let me know if you have further questions.
the following proposed code:
does not keep the contents of every line, rather only of the current line. You might want to change that
properly checks for errors
does not use dynamic memory allocation. You might want to change that
cleanly compiles
Does not include header files those contents are not used
Properly cleans up (closes files) when exiting either normally or when a call to sscanf() fails.
uses a valid signature for main()
uses the convention of defined values being in all capitals
properly uses MAX CHARACTERS modifier on the input format specifier %s so as to avoid any possibility of a buffer overflow and the resulting undefined behavior
documents why each header file is being included
does NOT correct the mismatch between the incoming data and the call to sscanf() Strongly suggest you read about atoi() and strtol() and modify the call to sscanf() to expect two char sequences and save them accordingly.
And now, the proposed code:
#include <stdio.h> // printf(), fprintf(), sscanf()
#include <stdlib.h> // exit(), EXIT_FAILURE
//#define MAX_LINES 100
#define MAX_LENGTH 14
int main( void )
{
char lines[ MAX_LENGTH +1];
char colour[ MAX_LENGTH ];
int value;
FILE *fp = fopen( "config2.txt", "r" );
if(fp == NULL)
{
perror( "fopen to read config2.txt failed" );
exit( EXIT_FAILURE );
}
while ( fgets( lines, MAX_LENGTH, fp ) )
{
if( sscanf(lines, "%100s %d", colour, &value) != 2 )
{
fprintf( stderr, "sscanf to extract two fields from input line failed\n" );
fclose( fp );
exit( EXIT_FAILURE );
}
printf( "colour: %s\n", colour );
printf( "value: %d\n", value );
}
fclose( fp );
return 0;
}
Your code is pretty close to something that works. The main problem is that you can not scan a line like "RED A" using the format specifier "%s %d" as A is not an integer. Instead you can scan it using a char.
Further you have a problem with the malloc of colour. You need to do sizeof(char*) as you want an array of char pointers.
So try something like:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define max 100
#define MAX_LENGTH 14
int main(){
char *filename = "config2.txt";
char *lines = malloc(max*sizeof(char));
char **colour = malloc(max*sizeof(char*)); // Use sizeof(char*)
char *value =malloc(max*sizeof(char)); // Use char instead of int
FILE *fp;
fp = fopen(filename, "r");
if(fp == NULL){
fprintf(stderr, "Cannot open %s : ", filename);
perror("");
exit(1);
}
int i= 0;
while (i < max && fgets(lines, MAX_LENGTH, fp) != NULL) {
colour[i] = malloc(MAX_LENGTH);
if (sscanf(lines, "%s %c", colour[i], &value[i]) != 2) // Use %c instead of %d and check return value
{
printf("Unexpected input file data\n");
exit(1);
}
printf("%s ", colour[i]);
printf("%c (%d)\n", value[i], value[i]); // Print value as both char and int
i++;
}
// Clean up
fclose (fp);
for (int j = 0; j<i; ++j) free(colour[j]);
free(colour);
free(value);
return 0;
}
Output:
RED A (65)
RED 2 (50)
RED 3 (51)
RED 4 (52)
RED 5 (53)
RED 6 (54)
RED 7 (55)
RED 8 (56)
RED 9 (57)
RED 1 (49)
RED J (74)
RED Q (81)
RED K (75)
Also notice that you should always check the return value of malloc. Example:
SomeType *someVar = malloc(sizeof(SomeType)); // or better malloc(sizeof *momeVar);
if (someVar == NULL)
{
// Out of memory - add error handling (e.g. terminate program)
}

Read till end of file into array

I've been trying to figure where I'm going wrong but I can't seem to point out where my error is exactly.
I'm trying to read from my text file, these integers
5 2 4 9 10 1 8 13 12 6 3 7 11
into an array A. To make sure it works, I was trying to print A but only getting large random numbers instead. Can someone help me see where i'm going wrong please?
int main(){
FILE* in = fopen("input.txt","r");
int A[100];
while(!feof(in)){
fscanf(in, "%s", &A);
printf("%d", A)
}
fclose(in);
return 0;
}
*this is just the main parts of the code related to the question
For all those who actually read why using feof is always wrong, the solution is something similar to the following. The code will open the filename given as the first argument to the program (or read from stdin by default):
#include <stdio.h>
enum { MAXI = 100 };
int main (int argc, char **argv) {
int i = 0, A[MAXI] = {0}; /* initialize variables */
/* read from file specified as argument 1 (or stdin, default) */
FILE *in = argc > 1 ? fopen (argv[1],"r") : stdin;
if (!in) { /* validate file opened for reading */
fprintf (stderr, "error: file open failed '%s'.\n", argv[1]);
return 1;
}
/* read each number from file or until array full */
while (i < MAXI && fscanf (in, " %d", &A[i]) == 1)
printf (" %d", A[i++]);
putchar ('\n');
if (in != stdin) fclose (in);
printf ("\n '%d' numbers read from the file.\n\n", i);
return 0;
}
Example Use/Output
Using your example values in the file dat/myints.txt results in the following:
$ ./bin/rdints dat/myints.txt
5 2 4 9 10 1 8 13 12 6 3 7 11
'13' numbers read from the file.

Resources