Simple C File IO Question (with code listing)
Simple C File IO Question (with code listing)
- Subject: Simple C File IO Question (with code listing)
- From: Sam Daniel <email@hidden>
- Date: Sun, 10 Jul 2005 21:04:59 -0700
Note: When this message posted, I did not see the attached files. The
listing of the main.c file is given below.
Following is a main.c file the uses two ways to input and output data.
1. The first loop reads 3 and writes 3 integers from and to stdin
and stdout, which works as expected.
2. The second loop is designed to read from an text file, input, and
write to text file output.
It fails and the program exits with signal 10.
This fragment of code worked fine years ago on a NextStation.
Can anyone see why it would fail when used to build a Standard Tool
with Xcode and how to resolve it?
If the main.c file and the two C text files are used to build a
Standard Tool and run, the first loop will ask the user to enter an
integer 3 times before proceeding to the second loop. At this point
the signal 10 is emitted. It is not clear whether the files, input
and output, have been opened properly for read and write,
respectively, nor that they were closed correctly. However, when all
statements having to do with these io files are commented out, the
program terminates as it should. The intent was to simply to write
the contents of input file to the output file. The output file
remains empty.
#include <stdio.h>
int main (int argc, const char * argv[])
{
FILE *input, *output;
int i, c, lines;
input = fopen( "input", "r" );
output = fopen( "output", "w" );
lines = 3;
for ( i = 0; i < lines; i++ ) {
while ( (c = getc(stdin)) != '\n') putc (c, stdout);
putc (c, stdout );
}
for ( i = 0; i < lines; i++ ) {
while ( (c = getc(input)) != '\n') putc (c, output);
putc (c, output );
}
fclose (input);
fclose (output);
return 0;
}
The input text file contains 3 lines
1
2
3
The output file is empty.
Sam Daniel
email@hidden
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Cocoa-dev mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden