• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

C help

Bluga

Banned

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);
}

 
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.
 
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);
 


<< 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.
 


<< 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?
 
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.
 


<< 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.
 
Back
Top