C/Interfacing VB with C
Expert: Narendra - 7/30/2007
QuestionI have a VB program which writes to a text file from a GUI. I then want my C program to read from that text file and then execute a command depending on whats in the file.
I thought this would be easy. Got the GUI set up, it writes either 1, 2 or a 3 to the text file.
I then came to writing my c program. As it stands it is:
#include <stdio.h>
void main()
{
int mychar = 0; /* Character for output */
int input;
FILE *fp;
/* Open the file for reading */
fp = fopen("c:\\myfile.txt", "r");
/* Read a character from the file */
fscanf(fp, "%d", &input);
fclose(fp); /* Close the file */
printf("%d\n", input);
switch (input)
{
case 1:
printf("run prog 1");
break;
case 2:
printf("run prog 2");
break;
case 3:
printf("run prog 3");
break;
default:
printf("o dear");
}
getchar();
}
It works when I read from a text file which I set up outside of VB, but when I use the text file which VB has written it seems to read a strange number, which when I open the text file is not there. For example the contents of the text file is 2
The c program reads that as -858993460.
What am I doing wrong? I thought initially it could be something to do with the way that VB writes to the file, and possibly leaves the file open so that the C program mis-reads it. But all research I can find doesn't mention anything about closing the text file in VB after writing to it.
Any help would be much appreciated.
Matt
AnswerLooking at the above code, I dont' see any problem.
One thing that you must add is, to check that fopen() returns a positive number as file descriptor.
I have never worked with VB. So, I have few questions on that:
1. How do you know that, VB is creating an ASCII file?
2. If you are using VB to create the file, then you will need to close the file, before opening again it for reading. Otherwise, your program may see incinsistent data.
I don't have VB here to test your code.
If you can upload the file that VB is creating to a place where I can download from, then I can try to see what type of file is that and what its contents look like.