Read file and only get integers and keep going till end - c

#include <stdio.h>
int getIntegers(char *filename,int a[]);
int main(void) {
/////
FILE *fp;
char file[10] = "random.txt";
fp = fopen(file, "w");
fprintf(fp, "1 2 -34 56 -98 42516547example-34t+56ge-pad12345\n");
fclose(fp);
/////
int i;
int a[100];
int n = getIntegers(file,a);
//Here i want to print out what i got from getIntegers. What it should put out = "1 2 -34 56 -98 42516547 -34 56 12345"
if (n > 0)
{
puts("found numbers:");
for(i = 0;i < n; i++)
{
printf("%d ",a[i]);
}
putchar('\n');
}
return 0;
}
int getIntegers(char *filename, int a[])
{
int c, i;
FILE *fp;
fp = fopen(filename, "r");
//I want what this code does to be done with the commented code under it. This will give "1 2 -34 56 -98 42516547"
while (fscanf(fp,"%d",&i)==1)
{
printf("%d ",i);
}
fclose(fp);
// I want this code to give "1 2 -34 56 -98 42516547 -34 56 12345"
// while ((c = fgetc(fp)) != EOF)
// {
// for(i = 0; i < c;i++)
// {
// fscanf(fp, "%1d", &a[i]);
// }
// }
// return i;
}
I have a file with numbers and words/letters in it. With this code I get the integers untill first letter, but i want to continue until EOF. And then return those numbers and print them out in main. I tried but could not get it to work. What should/could i do to get this working? Or what am I doing wrong.

Multiple issues:
int getIntegers() does not return any value. Code does not save anything in a[]. Array limits not enforced.
Commented code does not check the return value of fscanf().
Code needs to consume 1 character when fscanf() returns 0 and then try again.
When fscanf(fp, "%d", &a[i]) returns 0, it means the input is not numeric and fscanf() did not consume any of the non-numeric input. So read 1 character and try again.
#include <stdio.h>
#define N 100
int getIntegers(char *filename, int a[], int n);
int main(void) {
FILE *fp;
char file[] = "random.txt";
fp = fopen(file, "w");
if (fp == NULL) {
fprintf(stderr, "Unable to open file for writing\n");
return -1;
}
fprintf(fp, "1 2 -34 56 -98 42516547example-34t+56ge-pad12345\n");
fclose(fp);
int a[N];
int i;
int n = getIntegers(file, a, N);
puts("found numbers:");
for (i = 0; i < n; i++) {
printf("%d ", a[i]);
}
putchar('\n');
return 0;
}
int getIntegers(char *filename, int a[], int n) {
int i;
FILE *fp = fopen(filename, "r");
if (fp) {
for (i = 0; i < n; i++) {
int cnt;
do {
cnt = fscanf(fp, "%d", &a[i]);
if (cnt == EOF) { fclose(fp); return i; }
if (cnt == 0) fgetc(fp); // Toss 1 character and try again
} while (cnt != 1);
// printf("%d ", i);
}
fclose(fp);
}
return i;
}
Output
found numbers:1 2 -34 56 -98 42516547 -34 56 12345

Related

C - read TXT change from dup to fgets and sscanf

I read from txt pairs of numbers
How check it only 2 numbers in each line and not 3. I want show the line is the problem for example the pairs file:
3
25 35
14 42
30 60 70
Console: illegal input at line 4
I know That's not the correct way at all. Need use fgets to read and sscanf to parse.
I tried but the memory full garbage. How can I change it correctly?
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int i, c;
FILE *fp;
char str[100];
fp = fopen("./pairs.txt", "r");
if (dup2(fileno(fp), STDIN_FILENO < 0))
{
printf("Error opening file");
return -1;
}
if (feof(fp))
printf("Error reading file");
scanf("%d", &numOfPairs);
arrNum = (int *)malloc(sizeof(int) * numOfPairs * numbersInPair);
for (int i = 0; i < numOfPairs * numbersInPair; i += 2)
{
int num1, num2;
scanf("%d %d", &num1, &num2);
arrNum[i] = num1;
arrNum[i + 1] = num2;
}
}
Another try NOT working:
int main(int argc, char *argv[])
{
int index, i, numOfPairs;
int c;
FILE *file;
file = fopen("./pairs.txt", "r");
if ((c = getc(file)) == EOF)
{
perror("Error opening file"); //or return 1;
fclose(file);
}
while ((c = getc(file)) != EOF)
putchar(c);
{
fscanf(file, "%d", &numOfPairs);
allNumbers = (int *)malloc(sizeof(int) * numOfPairs * numbersInPair); //need multiply in 2 numbers for each pair
while (!feof(file) && numOfPairs > 0)
{
int x, y, arrIndex = 0;
numOfPairs--;
fscanf(file, "%d %d", &x, &y);
allNumbers[arrIndex] = x;
printf("The X : %d\n", x);
allNumbers[arrIndex + 1] = y;
printf("THE Y : %d\n", y);
arrIndex + 2;
}
fclose(file);
}

Thread 1: EXC_BAD_ACCESS (code=1, address=0x68 [duplicate]

I am new to C programming and I am getting a THREAD 1: EXC_BAD_ACCESS(code = 1, address 0x68)
when I run my program. The purpose of my code is to read from a txt file that contains positive and negative numbers and do something with it.
#include <stdio.h>
int main (int argc, const char * argv[]) {
FILE *file = fopen("data.txt", "r");
int array[100];
int i = 0;
int num;
while( fscanf(file, "%d" , &num) == 1) { // I RECEIVE THE ERROR HERE
array[i] = num;
printf("%d", array[i]);
i++;
}
fclose(file);
for(int j = 0; j < sizeof(array); j++){
printf("%d", array[j]);
}
}
After
FILE *file = fopen("data.txt", "r");
Say
if(file == 0) {
perror("fopen");
exit(1);
}
Just a guess, the rest of the code looks ok, so likely this is the problem.
Also worth noting that you might have more than 100 numbers in your file, in which case you will blow past the size of your array. Try replacing the while loop with this code:
for (int i = 0; i < 100 && ( fscanf(file, "%d" , &num) == 1); ++i)
{
array[i] = num;
printf("%d", array[i]);
}
Do you have the file "data.txt" created and local?
touch data.txt
echo 111 222 333 444 555 > data.txt
Check that your file open succeeded.
Here is a working version,
#include <stdio.h>
#include <stdlib.h> //for exit
int main (int argc, const char * argv[])
{
FILE *fh; //reminder that you have a file handle, not a file name
if( ! (fh= fopen("data.txt", "r") ) )
{
printf("open %s failed\n", "data.txt"); exit(1);
}
int array[100];
int idx = 0; //never use 'i', too hard to find
int num;
while( fscanf(fh, "%d" , &num) == 1) { // I RECEIVE THE ERROR HERE
array[idx] = num;
printf("%d,", array[idx]);
idx++;
}
printf("\n");
fclose(fh);
//you only have idx numbers (0..idx-1)
int jdx;
for(jdx = 0; jdx<idx; jdx++)
{
printf("%d,", array[jdx]);
}
printf("\n");
}

fprintf saves wrong data to file

I have an input file a.txt:
1 abc 3
2 efgh 4.5
3 text 3
4 xyz 2
So basically, it has 3 columns, first one is int, second is text, and third is double. I need to read this file by rows (which actually works, I guess), but have some problems with writing only second and third column to another (b.txt) file. fprinft saves something like this:
0.000000
0.000000
0.000000
0.000000
xvæ$ 0.000000
instead of
abc 3
efgh 4.5
text 3
xyz 2
I simply need to save only the second and the third column from a.txt file to b.txt file. Here's my code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct mypair
{
char string[1024];
double number;
} mypair;
void zero_string(char *string, int n)
{
int i;
for(i=0; i<n; i++)
string[i] = '\0';
}
int row(FILE* f, struct mypair *p)
{
int num;
if(!feof(f))
{
if(fscanf(f,"%d %s %lf", &num, p->string, &p->number) == 3)
{
return 0;
}
}
else
{
return 1;
}
}
int main(int argc, char **argv)
{
int n = 5, status = 0, i = 0, j;
struct mypair array[5];
char file_in_name[255];
char file_out_name[255];
FILE *fin;
FILE *fout;
zero_string(file_in_name, 255);
zero_string(file_out_name, 255);
printf("Data file:\n> ");
scanf("%s", file_in_name);
printf("Out file:\n> ");
scanf("%s", file_out_name);
fin = fopen(file_in_name, "r");
fout = fopen(file_out_name, "w");
if( fin == NULL )
{
exit(-1);
}
if( fout == NULL )
{
exit(-1);
}
while(status != 1)
{
status = row(fin, &array[i]);
i ++;
fprintf(fout, "%s %lf\n", array[i].string, array[i].number);
if(i >= n)
break;
}
fclose(fin);
fclose(fout);
for(j=0; j<i; j++)
printf("%s %lf\n", array[i].string, array[i].number);
return 0;
}
I modified the code, now it works, thanks!
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct mypair
{
char string[1024];
double number;
} mypair;
void zero_string(char *string, int n)
{
int i;
for(i=0; i<n; i++)
string[i] = '\0';
}
int row(FILE* f, struct mypair *p)
{
int num;
if(!feof(f))
{
if(fscanf(f,"%d %s %lf", &num, p->string, &p->number) == 3)
{
return 0;
}
}
else
{
return 1;
}
}
int main(int argc, char **argv)
{
int n = 5, status = 0, i = 0, j;
struct mypair array[5];
char file_in_name[255];
char file_out_name[255];
FILE *fin;
FILE *fout;
zero_string(file_in_name, 255);
zero_string(file_out_name, 255);
printf("Data file:\n> ");
scanf("%s", file_in_name);
printf("Out file:\n> ");
scanf("%s", file_out_name);
fin = fopen(file_in_name, "r");
fout = fopen(file_out_name, "w");
if( fin == NULL )
{
exit(-1);
}
if( fout == NULL )
{
exit(-1);
}
printf("\n");
while(status != 1)
{
status = row(fin, &array[i]);
if(i >= n)
break;
else
{
if(status != -1)
fprintf(fout, "%s %lf\n", array[i].string, array[i].number);
}
i ++;
}
fclose(fin);
fclose(fout);
for(j=0; j<i; j++)
printf("%s %lf\n", array[j].string, array[j].number);
return 0;
}
In your bottom loop, you want to index your array by j, not i.

Error when trying to read in numbers from txt file in C

I am new to C programming and I am getting a THREAD 1: EXC_BAD_ACCESS(code = 1, address 0x68)
when I run my program. The purpose of my code is to read from a txt file that contains positive and negative numbers and do something with it.
#include <stdio.h>
int main (int argc, const char * argv[]) {
FILE *file = fopen("data.txt", "r");
int array[100];
int i = 0;
int num;
while( fscanf(file, "%d" , &num) == 1) { // I RECEIVE THE ERROR HERE
array[i] = num;
printf("%d", array[i]);
i++;
}
fclose(file);
for(int j = 0; j < sizeof(array); j++){
printf("%d", array[j]);
}
}
After
FILE *file = fopen("data.txt", "r");
Say
if(file == 0) {
perror("fopen");
exit(1);
}
Just a guess, the rest of the code looks ok, so likely this is the problem.
Also worth noting that you might have more than 100 numbers in your file, in which case you will blow past the size of your array. Try replacing the while loop with this code:
for (int i = 0; i < 100 && ( fscanf(file, "%d" , &num) == 1); ++i)
{
array[i] = num;
printf("%d", array[i]);
}
Do you have the file "data.txt" created and local?
touch data.txt
echo 111 222 333 444 555 > data.txt
Check that your file open succeeded.
Here is a working version,
#include <stdio.h>
#include <stdlib.h> //for exit
int main (int argc, const char * argv[])
{
FILE *fh; //reminder that you have a file handle, not a file name
if( ! (fh= fopen("data.txt", "r") ) )
{
printf("open %s failed\n", "data.txt"); exit(1);
}
int array[100];
int idx = 0; //never use 'i', too hard to find
int num;
while( fscanf(fh, "%d" , &num) == 1) { // I RECEIVE THE ERROR HERE
array[idx] = num;
printf("%d,", array[idx]);
idx++;
}
printf("\n");
fclose(fh);
//you only have idx numbers (0..idx-1)
int jdx;
for(jdx = 0; jdx<idx; jdx++)
{
printf("%d,", array[jdx]);
}
printf("\n");
}

Structures and input from files

My text file is as following:
Random Words //this only appears once at the top
Occupation1
1 2 3 4 5
6 7 8 9 10
Occupation2
11 12 13 14 15
16 17 18 19 20
I am having some trouble with the input and was wondering if you could take a look at my code.
typedef struct foo
{
char occupation[256];
int numbers[limita][limitb];
}FOO;
void function(FOO input[]);
int main()
{
FOO input[limit];
function(input);
return 0;
}
void function(FOO input[])
{
FILE* file;
file = fopen("textfile.txt","r");
int a=0; int b =0;
char temp[81];
char randomwords[81];
while(fgets(temp,sizeof(temp)-1,file))
{
sscanf(temp, "%[^\n] %[^\n] %d", randomwords,&input[a].occupation[a], &input[a].numbers[a][b]);
a++;
}
}
So I tried printing out (with printf) the random words and the occupation but to no avail. I don't think i'm using numbers correctly at all as it has to be a 2D array and don't seem to be changing the columns.
I would really appreciate a step in the right direction/some help. Please explain simply. Thank you very much.
EDIT:
technomage brought up an interesting point regarding what i'm doing vs what I want. I'm not sure how to change in reflection to what he suggested though.
You probably want to do something like this. This implementation assumes that there are no blank lines in the input file. There are lot of hard coding here, you may want to make it better. I hope this helps you...
typedef struct foo
{
char occupation[256];
int numbers[2][5];
}FOO;
void function(FOO input[]);
void function(FOO input[])
{
FILE* file;
file = fopen("textfile.txt","r");
int a = 0, count, i;
char temp[81];
char randomwords[81];
if (file == NULL)
{
return;
}
fscanf(file, "%[^\n]\n", randomwords);
printf("%s\n", randomwords);
while (feof(file) != EOF)
{
i = 0;
i = fscanf(file, "%[^\n]\n", input[a].occupation);
if (i == -1)
break;
for (count=0; count < 5; count++)
{
i = 0;
i = fscanf(file, "%d", &(input[a].numbers[0][count]));
}
for (count=0; count < 5; count++)
{
i = 0;
i = fscanf(file, "%d", &(input[a].numbers[1][count]));
}
a++;
i = 0;
i = fscanf(file, "\n");
if (i == -1)
break;
};
fclose(file);
}
int main(int argc, char *argv[], char *envp[])
{
int i, j, count;
FOO input[10];
function(input);
for (count = 0; count < 2; count++)
{
printf("%s\n", input[count].occupation);
for (i = 0; i < 2 ; i++)
{
for (j = 0 ; j < 5 ; j ++)
{
printf ("%d ", input[count].numbers[i][j]);
}
printf ("\n");
}
printf ("\n");
}
}

Resources