C help

Bluga

Banned
Nov 28, 2000
4,315
0
0

I'm trying to read line by line (always two number) but i always get an compile error, anyone help me out?
======================================================
main()
{
FILE *fp1; /*file pointer */
FILE *fp2;
int *i, *j;

fp1 = fopen(Input_File, "r"); /* open input file */
fp2 = fopen(Output_File, "w"); /* opem output file */

if (fp1 == NULL)
printf("Cannot open %s\n", Input_File);
else
while(1) /*read in file */
{
i = fgets(int, sizeof(int), fp1);
j=fgets(int, sizeof(int), fp1);
fprintf( fp2, "%d\n", gcd(i, j) ); /* write to output */
}

fclose(fp1); /*close the file */
fclose(fp2);
}

 

Descartes

Lifer
Oct 10, 1999
13,968
2
0
You're using fgets() entirely wrong, for one. Here's the declaration:

char *fgets( char *string, int n, FILE *stream );

Try fscanf() to read your integers from the file.
 

Bluga

Banned
Nov 28, 2000
4,315
0
0

if i use fscanf(), i will always read in two numbers "together", how can i pass it to i, j? Thanks!
 

Descartes

Lifer
Oct 10, 1999
13,968
2
0
Each number is on a different line? Just do...

int i, j; // *i, *j won't work
fscanf(fp1, "%d", &i);
fscanf(fp1, "%d", &j);
 

Bluga

Banned
Nov 28, 2000
4,315
0
0


<< Each number is on a different line? Just do... >>



i mean each number on same line, for example:

1 2
3 4
5 6

i have to read two number each line.
 

Bluga

Banned
Nov 28, 2000
4,315
0
0


<< then do fscanf(fp1, "%d %d", &i, &j); >>



thanks, i forgot to mention i need to jump out of loop when encountering a blank line, fscanf() won't detect blank line. So i have to use fgets()? But them how can i read two numbers in one line?
 

singh

Golden Member
Jul 5, 2001
1,449
0
0
What you can do is read line by line using gets(). Then if you find that the line is no blank, decode the numbers using sscanf() which works like fscanf() only it will operate on a string that you give it.
 

Descartes

Lifer
Oct 10, 1999
13,968
2
0


<< What you can do is read line by line using gets() >>



:Q

I have to advise against the use of gets() under any circumstances. gets() is quite simply, evil. Lets have a look-see...

#include <stdio.h>

int main(void)
{
char buffer[10];
printf("Enter your name (10 characters only):");
gets(buffer);
printf("Hi %s\n", buffer);
return 0;
}

Now, I run the program...

> Enter your name: test
> Hi test

And all is well. But, if I do this...

> Enter your name: asdfasdfasdfasdfasdfasdf
> Hi asdfasdfasdfasdfasdfasdf

:Q I just overwrote EIP (known as a buffer overflow). Probably wouldn't be a big deal in your case, but lets not get into any habits, k? :) So, remember, gets() == evil, use fgets(). scanf() == evil, use fscanf(). Always, I repeat, always use a function that allows you to specify the bounds of the buffer you're feeding it. If not, you open yourself up to many security issues.