C++ App killing USB disk accsess? - c++

I've been working on this project, and I'll do my best to explain what I'm doing.
I will run a bat file from native DOS (USB DOS Boot thumbdrive) that starts a program (SHOWDATA.EXE) and outputs some data from that program to a text file. Then it will launch my app (compiled for DOS16Bit with Open-Watcom) which modifies a second exe file (EDITED.EXE) using information that was just previously output. Then it should run the newly modified exe (EDITED.EXE). My Environments for testing have been in Virtual Box and using a USB DOS bootable drive. So far my system and program runs as intended until the line where I display 'Finished' and want to Launch the newly modified exe, I get a
General failure reading drive C
Abort, Retry, Ignore, Fail?
Virtual Box here also displays a write Error to Drive A (Floppy drive A)
If I restart the system, I can then run the newly modified file without issue and have the desired results.
Is there a problem with the way I am opening or editing or closing my file that would cause this behavior?
#include <stdio.h>
#include <string.h>
int main(void)
{
FILE * pFile;
char data1[11];
char data2[33];
pFile = fopen ("testfile.exe","r+b");
printf ("PROGAM TITLE TEXT\n");
printf ("2013\n");
printf ("\n");
printf("Enter 10 Digit String from 1st filed above:\n"); //From previous program output
scanf ("%10s",data1); //only read 10 Chars
printf("Enter 32 Digits from 2nd field above:\n"); //From previous program output
scanf ("%32s",uuid); //only read 32 Chars
fseek (pFile,24523,SEEK_SET);//file offset location to begin write
fputs (sn,pFile); //Write our data!
fseek (pFile,24582,SEEK_SET);//file offset location to begin write
fputs (uuid,pFile); //Write our data!
fseek (pFile,24889,SEEK_SET);//file offset location to begin write
fputs (uuid,pFile); //Write our data!
fclose(pFile); //Close our file
printf ("Finished\n");
return(0);
}
My Bat file looks like this, where I pass a variable from text file "D.txt" to SHOWDATA.EXE and write the output to info.txt. I then parse info.txt with a FOR /F to display only useful information that will be used to edit the second exe file (EDITED.EXE). Then it will launch the edited exe file.
TYPE D.txt | SHOWDATA.EXE > Info.txt
PAUSE
MYPROGRAM.EXE
PAUSE
EDITED.EXE
I'm at a loss.

Related

C++ doesn't create text file

I'm new to the StackOverFlow.
I'm using Dev-C++ and I wanted to write a text file with my C++ program. But the problem is my program doesn't create a text file.
Instead it creates a file named "026.Writing-to-Files-With-Ofstream.o". (My cpp file's name is: 026.Writing-to-Files-With-Ofstream.cpp)
That's not what I wanted.
Also Dev-C++ doesn't give me any errors or warnings.
I tried using CodeBlocks and still the same result. It creates a ".o" file and not a text file.
Here is my code:
#include <iostream>
#include <fstream>
int main(){
std::ofstream file ("hello.txt");
file << "Hello There!"; //line 5
file.open("hello.txt"); //line 6
return 0;
}
I tried everything. Nothing in the desktop or in my working directory. I switched the lines (5 and 6). I really need your help.
You do too much.
std::ofstream file ("hello.txt");
This line creates ofstream and opens it for writing. When the stream is opened for writing, it's contents on disk is emptied!
file << "Hello There!";
This like prints something to the ofstream. Usually, it is stored in the buffer not yet saved to disk or displayed on screen. (To actually save something to disk, you need endl, flush, or to close the file. The file is closed when the block where it was opened ends, or when you close it explicitly.)
file.open("hello.txt"); //line 6
You again open the file for output, thus emptying it's contents on disk, and emptying the buffer.
}
whatever is in the buffer, saved to disk. But there is nothing in the buffer, because you opened the file again!
You should remove the line 6.
I see 2 problems here:
First, you just compiled the code so the output is a compiled object file called "026.Writing-to-Files-With-Ofstream.o". You need to run it.
Second, the code is not entirely correct. You already opened the file when you did std::ofstream file("hello.txt"); so you do not need line 6. You need to open the file before writing to it. Also You need to close the file after you finished writting: file.close();
I solved it! I searched all the Windows files/folders with the search option on the start menu. It took a long time (10 mins) but i finally found out where the file was. It was in the inside of a folder named "VTRoot". Thanks for the help tho

Is it possible to write and read from a text file with two programs simultaneously

If I have a program in c or c++ that writes to a particular text file and a program that reads from that same text file Is it possible for me to use the two programs simultaneously so that as the first program writes new data to the text file the other program can read it and detect the changes?
Any help would be appreciated.
Writing to a file:
if(fp)
{
// fp -> handle to the file
fputs("Satya Pawan Kartik", fp);
fclose(fp);
}
Reading from the file:
for(;;)
{
// fp -> handle to the file
while(fgets(line, sizeof line, fp))
{
printf("%s\n", line);
}
}
Let's say that the program writing to the text file is called write and the program reading the file is called read.
read obviously runs forever. Executing write displays the changes made by it to the text file by read. If required write can be modified to run forever and display the line written by it through a for loop counter. The same changes will be evidently visible in read.
So yes it is possible to write and read with 2 programs simultaneously.

Preventing Windows program from interpreting ^Z as end of file

My job is to translate a application from C -> C++ that have been installed on a linux distribution.so I wish the functionallity of C and linux.
I have a problem with reading binary file. It says that it reaches the EOF when it encounters a ctrl-Z character before it has reached the actual end of the file.
Precious execution in bash
zcat file.txt.gz | txtToBinary | binaryToOutput
Execution in command prompt
txtToBinary.exe < file.txt | binaryToOutput.exe
Raw text file
R 5643BYIDK DK0016060346 11DKKXKLY 160 1
R 10669VJK 98 1 IS0000004018 4ISKXICE 240 5000000
M814
txtToBinary.exe - Sample Output:
^#^#^# hello ^# ^Z^#^#^#^#
^#^#^[SWMA ^Y^YC
The problem is that the program interprets the first ^Z as the end of file.
Tried so far
My solutions has been to do the following when compiling on windows using c++
Execution in command prompt
txtToBinary.exe < file.txt | binaryToOutput.exe
int main(int argc, char* argv []){
int loop (args_t* args){
for (;;){
char data [1024];
int temp = read_msg (data, sizeof (data));
}
int read_msg(void* data, int size){
_setmode(_fileno(stdin), _O_BINARY);
_setmode(0,_0_BINARY);
if(fread(((unsigned char *)data)+sizeof(*hdr),hdr->size-sizeof (*hdr),1,stdin) != 1);
if(feof(stdin))
printf("End of file error\n");
}
I have also tried Cygwin which some of the answers have me. But that also failed.
StackOverflow Answers
When looking at answer here in SO, we see Windows, Windows EOF, Binary solution,Binary Mode and Stream data end at byte 26 and Reaching EOF early Windows. They tell me that:
- Windows keys (CTRL + Z, ^Z) makes an end of file
- I have to read in binary format
I found the answer to my question. It had to do with where you read from. You need to put
_setmode(0,_0_BINARY);
in the main() function!!!!!!!! Remember this, otherwise other reads or writes will not be included.
fread() is part of stdio. What you're doing is opening the raw file as binary, but then doing text-mode standard I/O.
You could replace your existing fread() call with the read() system call. (That is, fread() is a library call that does some buffering, ultimately to call through to read().)

.exe file throws exception when opening file

I'm trying to write a CGI script in c++ which prints the reverse network path (using
traceroute) from the web server to the IP address of the client invoking the CGI script.
When I run the program in Visual Studio, it works fine(creates the process, prints the result into "C:/result.out" file, opens the file, prints each line from file, closes file) BUT after compiling and trying to run just its .exe file, it throws an exception. What could I do to make the .exe work properly ?
Just as a note, I'm using Windows XP and Visual C++ 2008
Here`s the code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <process.h>
#include <conio.h>
int main()
{
char *line, *command, *userIp;
printf("Content-Type:text/html\n\n");
printf("<html><head></head><br/>");
printf("<body><br/>");
line = (char*)malloc(255*sizeof(char));
command = (char*)malloc(10*sizeof(char));
userIp = (char*)malloc(30*sizeof(char));
//userIp = getenv("REMOTE_ADDR"); // use a default IP until program works
strcpy(command,"tracert ");
strcpy(userIp,"74.125.87.104");
strcat(command,userIp);
strcat(command," > C:/result.out");
// create command "tracert 74.125.87.104 > C:/result.out"
printf("%s",command);
system(command);
FILE *f;
f = fopen("C:/result.out","r"); // open C:/result.out and read line - by - line
strcpy(line,"");
while(!feof(f)){
fgets(line,255,f);
printf("%s\n",line);
}
fclose(f);
printf("<br/>Test running OK<br/>");
printf("</body></html>");
getch();
return 0;
}
Most likely your web server (sanely) doesn't have permission to write to c:\. Either use a proper location for temporary files, or have tracert stream the results back to the executable so you can capture them.
Well the following two lines cause buffer over-runs
strcat(command,userIp);
strcat(command," > C:/result.out");
So this is likely the result of a crash.
Please do not use the term "Exception" unless an exception is being thrown, and since you are writing C code that is unlikely. So it is not an exception.
Rather than running a command using system() and piping the result to a file use the popen() command this will run a command and pipe the output to a stream that you can read just like a file (but without the security implications of writing to the file system).
FILE *f;
f = popen(command,"r"); // run the command. The std out goes to the FILE stream
^^^^^^
strcpy(line,"");
while(!feof(f)){
fgets(line,255,f);
printf("%s\n",line);
}
fclose(f);

Difference between files written in binary and text mode

What translation occurs when writing to a file that was opened in text mode that does not occur in binary mode? Specifically in MS Visual C.
unsigned char buffer[256];
for (int i = 0; i < 256; i++) buffer[i]=i;
int size = 1;
int count = 256;
Binary mode:
FILE *fp_binary = fopen(filename, "wb");
fwrite(buffer, size, count, fp_binary);
Versus text mode:
FILE *fp_text = fopen(filename, "wt");
fwrite(buffer, size, count, fp_text);
I believe that most platforms will ignore the "t" option or the "text-mode" option when dealing with streams. On windows, however, this is not the case. If you take a look at the description of the fopen() function at: MSDN, you will see that specifying the "t" option will have the following effect:
line feeds ('\n') will be translated to '\r\n" sequences on output
carriage return/line feed sequences will be translated to line feeds on input.
If the file is opened in append mode, the end of the file will be examined for a ctrl-z character (character 26) and that character removed, if possible. It will also interpret the presence of that character as being the end of file. This is an unfortunate holdover from the days of CPM (something about the sins of the parents being visited upon their children up to the 3rd or 4th generation). Contrary to previously stated opinion, the ctrl-z character will not be appended.
In text mode, a newline "\n" may be converted to a carriage return + newline "\r\n"
Usually you'll want to open in binary mode. Trying to read any binary data in text mode won't work, it will be corrupted. You can read text ok in binary mode though - it just won't do automatic translations of "\n" to "\r\n".
See fopen
Additionally, when you fopen a file with "rt" the input is terminated on a Crtl-Z character.
Another difference is when using fseek
If the stream is open in binary mode, the new position is exactly offset bytes measured from the beginning of the file if origin is SEEK_SET, from the current file position if origin is SEEK_CUR, and from the end of the file if origin is SEEK_END. Some binary streams may not support the SEEK_END.
If the stream is open in text mode, the only supported values for offset are zero (which works with any origin) and a value returned by an earlier call to std::ftell on a stream associated with the same file (which only works with origin of SEEK_SET.
Even though this question was already answered and clearly explained, I think it would be interesting to show the main issue (translation between \n and \r\n) with a simple code example. Note that I'm not addressing the issue of the Crtl-Z character at the end of the file.
#include <stdio.h>
#include <string.h>
int main() {
FILE *f;
char string[] = "A\nB";
int len;
len = strlen(string);
printf("As you'd expect string has %d characters... ", len); /* prints 3*/
f = fopen("test.txt", "w"); /* Text mode */
fwrite(string, 1, len, f); /* On windows "A\r\nB" is writen */
printf ("but %ld bytes were writen to file", ftell(f)); /* prints 4 on Windows, 3 on Linux*/
fclose(f);
return 0;
}
If you execute the program on Windows, you will see the following message printed:
As you'd expect string has 3 characters... but 4 bytes were writen to file
Of course you can also open the file with a text editor like Notepad++ and see yourself the characters:
The inverse conversion is performed on Windows when reading the file in text mode.
We had an interesting problem with opening files in text mode where the files had a mixture of line ending characters:
1\n\r
2\n\r
3\n
4\n\r
5\n\r
Our requirement is that we can store our current position in the file (we used fgetpos), close the file and then later to reopen the file and seek to that position (we used fsetpos).
However, where a file has mixtures of line endings then this process failed to seek to the actual same position. In our case (our tool parses C++), we were re-reading parts of the file we'd already seen.
Go with binary - then you can control exactly what is read and written from the file.
In 'w' mode, the file is opened in write mode and the basic coding is 'utf-8'
in 'wb' mode, the file is opened in write -binary mode and it is resposible for writing other special characters and the encoding may be 'utf-16le' or others