#include "stdafx.h"
#include "string.h"
#include "stdio.h"
void CharReadWrite(FILE *fin);
FILE *fptr2;
int _tmain(int argc, _TCHAR* argv[])
{
char alpha= getc(stdin);
char filename=alpha;
if (fopen_s( &fptr2, filename, "r" ) != 0 )
printf( "File stream %s was not opened\n", filename );
else
printf( "The file %s was opened\n", filename );
CharReadWrite(fptr2);
fclose(fptr2);
return 0;
}
void CharReadWrite(FILE *fin){
int c;
while ((c=fgetc(fin)) !=EOF) {
putchar(c);}
}
views:
1411answers:
4
+1
A:
A character (ASCII) is just an unsigned 8 bit integral value, ie. it can have a value between 0-255. If you have a look at an ASCII table you can see how the integer values map to characters. But in general you can just jump between the types, ie:
int chInt = getc(stdin);
char ch = chInt;
// more simple
char ch = getc(stdin);
// to be explicit
char ch = static_cast<char>(getc(stdin));
Edit: If you are set on using getc to read in the file name, you could do the following:
char buf[255];
int c;
int i=0;
while (1)
{
c = getc(stdin);
if ( c=='\n' || c==EOF )
break;
buf[i++] = c;
}
buf[i] = 0;
This is a pretty low level way of reading character inputs, the other responses give higher level/safer methods, but again if you're set on getc...
DeusAduro
2009-07-17 23:32:24
getc returns an `int` for a reason. `EOF` will not generally fit in a `char`.
Logan Capaldo
2009-07-17 23:35:43
would you take a look at the above code? I always get error messages when I tried to compile them
2009-07-17 23:37:46
good point, so to be safe verify that the return value is not EOF, before casting to a char.
DeusAduro
2009-07-17 23:37:51
Thanks Deus, but i don't think the bug is with my CharReadWrite function. I've commented out the portion, but i get error C2664: 'fopen_s' : cannot convert parameter 2 from 'char' to 'const char *'
2009-07-17 23:44:22
+2
A:
Continuing with the theme of getc you can use fgets
to read a line of input into a character buffer.
E.g.
char buffer[1024];
char *line = fgets(buffer, sizeof(buffer), stdin);
if( !line ) {
if( feof(stdin) ) {
printf("end of file\n");
} else if( ferror(stdin) ) {
printf("An error occurerd\n");
exit(0);
}
} else {
printf("You entered: %s", line);
}
Note that ryansstack's answer is a much better, easier and safer solution given you are using C++.
Logan Capaldo
2009-07-17 23:42:25