go away spammer

Author Topic: fprintf() problem in C  (Read 7076 times)

0 Members and 1 Guest are viewing this topic.

Offline AdminTopic starter

  • Administrator
  • Supreme Robot
  • *****
  • Posts: 11,703
  • Helpful? 173
    • Society of Robots
fprintf() problem in C
« on: August 27, 2007, 08:16:35 PM »
I am trying to do a simulation using C with this compiler:
http://www.bloodshed.net/devcpp.html
(I believe it uses gcc)

So I compile my code with no problem, and it gives me an .exe. I run the file, it flashes a command prompt for about .05 seconds, then disappears . . .

Anyone know how to fix that so I can see the printf'd data output?

So I got the 'genious' idea that maybe if I fprintf out the data to a .txt file I can see the results of my simulation.

But when I add the line 'fprintf("results.txt","Starting Wavefront\n\r");', it displays 'Starting Wavefront' then brings up a windows crash error. Sigh.

So what am I doing wrong?

Source code here (its a short program):
Code: [Select]
//WAVEFRONT ALGORITHM

#include <stdlib.h>

//in main, declare map matrix //6x6 map
int nothing=0;
int wall=255;
int goal=1;
int robot=254;

int robot_x=4;
int robot_y=4;

//map locations
int x=0;
int y=0;

//temp variables
int temp_A=0;
int temp_B=0;

//when searching for a node with a lower value
int minimum_node=250;

int map[6][6]= {{0,0,0,0,0,0},
{0,0,0,0,0,0},
{0,0,0,0,0,0},
{0,0,0,0,0,0},
{0,0,0,0,0,0},
{0,0,0,0,0,0}};

//declare functions here, first
void propagate_wavefront(int robot_x, int robot_y);
void unpropagate(int robot_x, int robot_y);
void trace_path(int x, int y);
int min_surrounding_node_value(int x, int y);
void print_map(void);

int main(void)
{
    fopen("results.txt","w");
printf("Starting Wavefront\n\r");
fprintf("results.txt","Starting Wavefront\n\r");

//declare robot location and start propagation
propagate_wavefront(5, 3);

fclose("results.txt");

return 0;
}


void propagate_wavefront(int robot_x, int robot_y)
{
//clear old wavefront
unpropagate(robot_x, robot_y);

//old robot location was deleted, store new robot location in map
map[robot_x][robot_y]=robot;


printf("now unpropagated\n\r");

//start location to begin scan at goal location
map[2][0]=goal;
x=2;
y=0;

while(x<6 || y<6)//while the map hasnt been fully scanned
{
//if this location is a wall or the goal, just ignore it
if (map[x][y] != wall && map[x][y] != goal)
{
//a full trail to the robot has been located, finished!
if (min_surrounding_node_value(x, y) < 250 && map[x][y]==robot)
{
trace_path(x,y);//tell robot to start moving down path
return;
}

//record a value in to this node
else
map[x][y]=minimum_node+1;

}

//go to next node and/or row
x++;
if (x==6)
{
y++;
x=0;
}
}

print_map();
}

void unpropagate(int robot_x, int robot_y)//clears old path to determine new path
{
x=0;
y=0;

//stay within boundary
while(x<6 || y<6)//while the map hasnt been fully scanned
{
if (map[x][y] != wall) //if this location is a wall, just ignore it
{
if (map[x][y] != goal)
map[x][y] = nothing;//clear that space
}
//go to next node and/or row
x++;
if (x==6)
{
y++;
x=0;
}
}
}

void trace_path(int x, int y)
{
//look at robot location
//find minimum value around robot
//min_surrounding_node_value(x, y)
printf("\n\r finished");
fprintf("results.txt", "\n\r finished");

//send move command to robot to that location
//robot_move(to that location)
}


//this function looks at a node and returns the lowest value around that node
int min_surrounding_node_value(int x, int y)
{
minimum_node=250;//reset minimum

//right
if(x+1 < 6)//not out of boundary
if  (map[x+1][y] < minimum_node && map[x+1][y] != nothing)//find the lowest number node, and exclude empty nodes (0's)
minimum_node = map[x+1][y];

//left
if(x-1 >= 0)
if  (map[x-1][y] < minimum_node && map[x-1][y] != nothing)
minimum_node = map[x-1][y];

//top
if(y+1 < 6)
if  (map[x][y+1] < minimum_node && map[x][y+1] != nothing)
minimum_node = map[x][y+1];

//bottom
if(y-1 >= 0)
if  (map[x][y-1] < minimum_node && map[x][y-1] != nothing)
minimum_node = map[x][y-1];

return minimum_node;
}

void print_map(void)
{
for (temp_B=0;temp_B<6;temp_B++)
{
for (temp_A=0;temp_A<6;temp_A++)
{
printf("%d",map[temp_A][temp_B]);//print out the X row first

        fprintf("results.txt", "%d",map[temp_A][temp_B]);
}
printf("\n\r");//then go to next line Y
fprintf("results.txt", "\n\r");
}
}


/*
pseudocode

start at top left
if node == robot
end
else if node == wall
ignore

else
check 4 sides
save lowest number (nothing=0 doesnt count)
set current node as lowest number + 1
go to next node
*/

Offline DomoArigato

  • Full Member
  • ***
  • Posts: 54
  • Helpful? 1
Re: fprintf() problem in C
« Reply #1 on: August 27, 2007, 08:46:21 PM »
Have you tried putting a pause at the end of the console output?

paulstreats

  • Guest
Re: fprintf() problem in C
« Reply #2 on: August 27, 2007, 09:50:30 PM »
try this:

Code: [Select]
char output1 = "P";
FILE *out;   
out = fopen( "output.txt", "w" );   
if( out != NULL )     
fprintf( out, "output = ", output1 );

First of all you have to open the output file here, and then print to it.  fprintf only appends files, it doesnt make them, and it also doesnt set up its own output stream, this is what FILE does. You will probably have to include close out; afterwards

Also using this code, you have to have the file output.txt already made, ie i dont think the code will generate the file (some languages will search for the file and if not present create it, others will search and if not present leave out as null and return a file not found exception / error.

Also another way to just see your code, did you try putting a simple while(1) loop at the end of your main(). This will prevent the program from exiting i think.

Offline cybcode

  • Jr. Member
  • **
  • Posts: 18
  • Helpful? 0
Re: fprintf() problem in C
« Reply #3 on: August 27, 2007, 11:57:42 PM »
As far as I know, fprintf will happily write whatever you ask it to (not just chars), and it will create the file if it doesn't exist.

The following code works for me, both when the file exists and when it doesn't, and I see no reason for it not to work with all other C compilers:

Code: [Select]
int output_int = 14 ;
float output_float = 0.3674522322 ;
char *output_string = "moooooooooo\n" ;

FILE *fp ;
fp = fopen( "output.txt" , "w" ) ;
if( fp )
{
fprintf( fp , "hello world %d %f %s\n" , output_int , output_float , output_string ) ;
fclose( fp ) ;
}

"if( fp )" is equivalent to "if( fp != NULL )". The "if( fp )" is not really necessary because there's no reason for the fopen call to fail (unless the file exists and is write protected) - it's just good programming practice.


Another way to solve your problem would be to with getch() if your compiler supports it (some compilers don't apparently). To use it, #include <conio.h> and call getch() at the end of your main() function. It will return when any key is pressed.

Another way would be to use getchar(). You don't need to #include anything new for it (other than stdio.h). It will return after pressing enter, or after typing some stuff and then pressing enter (based on my experimentation with it - your experience may differ).

Another way is cin.get(). #include <iostream> and then call std::cin.get(). It will return like getchar().

Another way would be to use scanf, but then you would have to enter some real input and press enter - enter alone will not suffice, which is annoying.
« Last Edit: August 28, 2007, 12:07:57 AM by cybcode »

Offline snow

  • Full Member
  • ***
  • Posts: 73
  • Helpful? 0
Re: fprintf() problem in C
« Reply #4 on: August 28, 2007, 01:23:00 AM »
Add:
Code: [Select]
system("pause");before the final return.

Offline AdminTopic starter

  • Administrator
  • Supreme Robot
  • *****
  • Posts: 11,703
  • Helpful? 173
    • Society of Robots
Re: fprintf() problem in C
« Reply #5 on: August 28, 2007, 04:54:17 AM »
Still having problems . . .

so I put this in my main:
Code: [Select]
    FILE *out ;
    out = fopen("results.txt","w");
    if( out != NULL )
            fprintf(out,"Starting Wavefront\n\r");
    printf("Starting Wavefront\n\r");

but it gives me this error when compiling:
'FILE' undeclared (first use in this function)
'out' undeclared (first use in this function)

Should I define these somewhere else?

I also added in system("pause"); but with no effect :-\

Offline cybcode

  • Jr. Member
  • **
  • Posts: 18
  • Helpful? 0
Re: fprintf() problem in C
« Reply #6 on: August 28, 2007, 06:07:46 AM »
Did you #include <stdio.h>?

Did you try getchar()?

BTW, you don't need \r at the end of every string you send to printf. If you want to start a new line \n is enough.
« Last Edit: August 28, 2007, 06:12:06 AM by cybcode »

Offline dunk

  • Expert Roboticist
  • Supreme Robot
  • *****
  • Posts: 1,086
  • Helpful? 21
    • dunk's robot
Re: fprintf() problem in C
« Reply #7 on: August 28, 2007, 07:51:12 AM »
Quote
So I compile my code with no problem, and it gives me an .exe. I run the file, it flashes a command prompt for about .05 seconds, then disappears . . .
your launching the complied program directly from windows right?
the program finishes executing so windows closes the window.
this is the expected behaviour.

try running it from the command prompt instead.
that way the text your program displays will still be visible in the command prompt window.

dunk.

Offline snow

  • Full Member
  • ***
  • Posts: 73
  • Helpful? 0
Re: fprintf() problem in C
« Reply #8 on: August 28, 2007, 07:55:53 AM »
You say this code:

Code: [Select]
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
  printf("Pause test\n");
  system("PAUSE");
  return 0;
}

closes on it own?

Offline dunk

  • Expert Roboticist
  • Supreme Robot
  • *****
  • Posts: 1,086
  • Helpful? 21
    • dunk's robot
Re: fprintf() problem in C
« Reply #9 on: August 28, 2007, 08:47:56 AM »
Quote
You say this code:
....
closes on it own?
why would that close on it's own?
the program does not finish executing.

i was referring to Admins original post.

dunk.

Offline snow

  • Full Member
  • ***
  • Posts: 73
  • Helpful? 0
Re: fprintf() problem in C
« Reply #10 on: August 28, 2007, 03:39:31 PM »
And i was referring to:
Quote
I also added in system("pause"); but with no effect

Offline dunk

  • Expert Roboticist
  • Supreme Robot
  • *****
  • Posts: 1,086
  • Helpful? 21
    • dunk's robot
Re: fprintf() problem in C
« Reply #11 on: August 28, 2007, 04:30:51 PM »
hey Snow,
hehe.
so you were.
my bad.

dunk.
(looking for the forum's "roll back time" button.)

Offline AdminTopic starter

  • Administrator
  • Supreme Robot
  • *****
  • Posts: 11,703
  • Helpful? 173
    • Society of Robots
Re: fprintf() problem in C
« Reply #12 on: August 28, 2007, 05:17:20 PM »
Ive made progress, but still having issues . . .

Quote
Did you #include <stdio.h>?
oops, nope forgot. Ok I added it and it no longer crashes . . .


This is the relevant code:
Code: [Select]
FILE *out ;

int main(void)
{
out = fopen("results.txt","w");
if( out != NULL )
fprintf(out,"Starting Wavefront\n\r");
printf("Starting Wavefront\n\r");

//declare robot location and start propagation
propagate_wavefront(5, 3);

fclose(out);
system("PAUSE");
return 0;
}

It still closes on its own despite that pause. I tried Dunks suggestion by running the program from a command prompt and I get this:
Quote
C:\Documents and Settings\Pika\Desktop\MyRobots\iRobot Create>wave_front_simulation.exe
Starting Wavefront

On the bright side, it DOES create a file called results.txt. Unfortunately, it does not write anything in to it . . .

Ideas?

paulstreats

  • Guest
Re: fprintf() problem in C
« Reply #13 on: August 28, 2007, 06:20:32 PM »
Quote
if( out != NULL )
      fprintf(out,"Starting Wavefront\n\r");

try:

if(out)
{
fprintf(out,"Starting Wavefront \n \r");
}

you may also want to try \n \r before printing the first line out.

Also when using the return carriage / new line commands compilers can be different. some need you to return carriage before you create a new line and others the other way around, i have been caught out with this a couple of times - it can really mess up database tables

Offline AdminTopic starter

  • Administrator
  • Supreme Robot
  • *****
  • Posts: 11,703
  • Helpful? 173
    • Society of Robots
Re: fprintf() problem in C
« Reply #14 on: August 28, 2007, 06:27:03 PM »
never mind . . .

so i put a billion debugging printf statements into my code and found an infinite loop.

apparently, when you have an infinite loop, the program closes without an error message . . .

after fixing the loop, everything worked properly (mostly)

Offline cybcode

  • Jr. Member
  • **
  • Posts: 18
  • Helpful? 0
Re: fprintf() problem in C
« Reply #15 on: August 28, 2007, 11:53:05 PM »
Does it completely work now or are you still having problems?

When you say the file remains empty, do you mean it doesn't even contain the text "Starting Wavefront"?

What's wrong with what you got when you ran the program from a command prompt?

Try adding this:
Code: [Select]
getchar();
before the final return.

Also, it's possible that your program does something illegal inside the function "propagate_wavefront", and therefore crashes immediately, and never gets to system("pause"). (an infinite loop is not illegal.) To be very sure you should run the program from a command line, like you did.

Offline AdminTopic starter

  • Administrator
  • Supreme Robot
  • *****
  • Posts: 11,703
  • Helpful? 173
    • Society of Robots
Re: fprintf() problem in C
« Reply #16 on: August 29, 2007, 07:02:39 AM »
Quote
Does it completely work now or are you still having problems?
The pause works, and it now puts stuff in to a text file. All that is solved.

The reason why I said 'mostly' is because the algorithm itself has this mysterious bug I cant figure out. It has to do with propagating a wavefront in a matrix. If anyone wants to give it a look:
http://www.societyofrobots.com/robotforum/index.php?topic=1754.msg12406#msg12406

Offline crossroads1946

  • Jr. Member
  • **
  • Posts: 21
  • Helpful? 0
Re: fprintf() problem in C
« Reply #17 on: September 03, 2007, 11:28:20 AM »
As for the program exiting when hitting an infinite loop...
GCC (which is basically what you're using) has a ton of optimization that it can do. It's a pretty smart complier so when it comes upon code that it knows won't do anything (such as an infinite loop in this case), it will optimize it out the code completely. I'm not familiar with the IDE you're using, but you should probably be able to find optimization settings in there somewhere.

Or, if it gives you a place to enter compiler parameters, check out http://www.gnu.org/software/gcc/onlinedocs/ under section 3.10. For debugging, use the -O0 (that's dash Oh zero) to turn off all optimization. If you need to figure out what version of GCC you're using, from a command prompt, type "gcc -v".

Baker
« Last Edit: September 03, 2007, 11:29:03 AM by crossroads1946 »

Offline rgcustodio

  • Robot Overlord
  • ****
  • Posts: 217
  • Helpful? 0
  • Use "Search" and ye might find answers!
Re: fprintf() problem in C
« Reply #18 on: September 12, 2007, 03:37:16 PM »
Admin, the "pause" is unnecessary. Use a fflush() instead.
The best thing one can do when it's raining is to let it rain. - H. W. Longfellow

understanding is the path to enlightenment

 


Get Your Ad Here