I am trying to get some text entered from the console written into a file called "output.txt" with the following code..
#include <stdio.h>
#include <stdlib.h>
int main()
{
printf("write something\n");
char c;
FILE *output=fopen("output.txt","w");
if(!output)
{
printf("couldn't open file\n");
return 1;
}
while(c=getchar())
fprintf(output,"%c",c);
fclose(output);
}
but the "output.txt" file contains no text when i open it. Why is this happening?
All help is highly appreciated .
Since you do not have a proper exit condition in your loop, the only way to terminate your program is by forcefully ending the process. This means that there is no guarantee that any pending buffered output will be written to the stream output.
What you can do is change your loop condition to while((c = getchar()) != EOF). Then, you can use the characters Ctrl+Z (Windows) or Ctrl+D (*nix) to make the loop condition false, reaching the line fclose(output), which will flush the buffer and close the file.
Also, make c an int, since that's what EOF is.
You probably want something like this:
...
while ((c = getchar()) != 'X')
fprintf(output, "%c", c);
fclose(output);
...
Input:
ABCXEnter
Output.txt will contain ABC.
Related
i wanted to ask you, how to read from file using in C language:
your_program <file.txt
cat file.txt
Line one
Line two
Line three
i have something like that, but it is not working. Thanks a lot
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int vstup;
input = getchar();
while( input != '\n')
printf("End of line!\n");
return 0;
}
You could use freopen() to make stdin refer to the input file instead of the keyboard.
This can be used for input or output redirection.
In your case, do
freopen("file.txt", "r", stdin);
Now stdin is associated with the file file.txt and when you read using functions like scanf(), you are actually reading from file.txt.
freopen() will close the old stream (which is stdin here) "otherwise, the function behaves just like fopen()". It will return NULL if some error occurred. So you better check the value returned by freopen().
Read more about freopen() here and here.
And as others have pointed out, the code as you posted it is probably having an infinite loop as the value of input never changes inside the loop.
compile/link the proposed code into some file, lets call that executable: run
when running the following proposed code, redirect 'stdin' from the input file
./run < file.txt
Here is the proposed code:
// <<-- document why a header is being included
#include <stdio.h> // getchar(), EOF, printf()
//#include <stdlib.h> <<-- don't include header files those contents are not used
int main( void ) // <<-- since the 'main()' parameters are not used,
// use this signature
{
int input; // <<-- 'getchar()' returns an integer and EOF is an integer
while( (input = getchar() ) != EOF ) // <<-- input one char per loop until EOF
{
if( '\n' == input ) // is that char a newline?
{
printf("End of line!\n"); // yes, then print message
}
}
return 0;
} // end function: main <<-- document key items in your code
I have the following code:
#include <stdio.h>
int main()
{
char c = 0;
fclose(stdin);
stdin = fopen("newin", "r");
if(stdin != NULLL)
{
scanf("%c", &c);
printf("%d", c);
}
else
printf("Error");
}
I want my program to wait for a change in the stdin file. I created it blank, but it returns 0.
If a put like a 'a' char in it it prints 97 like it should.
How can I make the scanf wait for a change in the file, like it was waiting for me to write in the terminal window?
How can I make the scanf wait for a change in the file, like it was waiting for me to write in the terminal window?
You can't.
Input from stdin and a file from disk are handled differently. When you are reading from a file, the file must have everything in order before you open it to read from it.
it's a very simple question, how to echo every char that I type in stdin to stdout? I'm trying to do it for a long time and I've tried many ways and no one works well. The best I could do was to get what I typed after application end.
The best I did was:
#include <stdio.h>
int main()
{
while (1)
{
int ch = getc(stdin);
if(ch == EOF) break;
putc(ch, stdout);
}
return 0;
}
Thanks.
You need to flush the stdout:
int main()
{
while (1)
{
int ch = getc(stdin);
fflush(stdout);
if(ch == EOF) break;
putc(ch, stdout);
}
return 0;
}
The code you have should work just fine, as long as you hit enter. In most systems, the program will get input in a line oriented fashion. If you want to echo the key immediately after it is hit, you will need to change the input method for the program. On many systems, this would be getch(), but there may be other requirements you have to satisfy before you can use the interface (ncurses requires some additional setup, for example).
When echoing the data immediately after the key is hit, you will be required to flush the output in some way. If you are sending the output to stdout, then a call to fflush() will work. If you are using some system specific output command, you may be required to call some kind or window refresh routine.
I wonder if a better way would be:
int ch;
while((ch = getchar()) >= 0)
{
putchar(ch);
}
Then if you call this:
echo this is my input | ./myprogram
it would output the entire stdin this is my input without hitting the enter key.
I need to write the Solaris the 'line' application on Solaris, which is very simple, on Linux. It was developed for scripting, it takes one line of stdin and outputs it to stdout. I wrote an extraordinarily simple C program to do this. I used both getline and fgets and they produce the same outcome:
int main(int argc, char* argv[])
{
char buf[256];
char* line = NULL;
if (fgets(line, 256, stdin) != NULL)
//if (getline(&line, &len, stdin) != -1)
{
printf("%s", line);
}
return EXIT_SUCCESS;
}
The C-Shell script, loop_file looks like this:
#!/bin/csh -f
while(1)
set line = `app`
echo "Got Line : $line"
end
I kick off the process using the following:
./loop_file < textFile.txt
It's a large file, the first line is printed out just but the next line is almost 4096 characters after, the third line is almost 4096 after that, etc. It is not a line-by-line read. I've even tried forgetting using C and using awk in the while loop instead.
Any ideas?
By the way, don't say - don't use CSH - it's legacy code I'm required to port :)
while(1)
set line = `app`
set name = $line[0];
set address = $line[1];
set purpose = $line[2];
end
stdin is buffered which could be the reason why some of the lines from the text file are missed out. You could possibly make stdin unbuffered using setvbuf(fd, NULL, _IONBF, 0) or equivalent before fgets call in your C program and address this issue.
Alternatively, you can read character by character following the suit of line utility. Maybe something on the lines of :
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int main(void)
{
char c;
while(read(STDIN_FILENO , &c, 1) > 0 && c != '\n')
putchar(c);
return EXIT_SUCCESS;
}
Hope this helps!
While doing filing im stuck here.The condition of the while loop is not working.The compiler says cannot convert int to FILE*.
while(pFile!=EOF);
Should i typecase the pFile to int?I tried that but it did not worked.Thanks in advance.
The complete code is:
int main()
{
char ch;
char name[20];
FILE *pFile;
int score;
pFile=fopen("database.txt","r");
if(pFile!=NULL)
{
while(pFile!=EOF);
{
fscanf(pFile,"%c",ch);
}
}
else
printf("Cant open the file.......");
fclose(pFile);
return 0;
}
First, you do not want to use while (!feof(pFile)) -- ever! Doing so will almost inevitably lead to an error where the last data you read from the file appears to be read twice. It's possible to make it work correctly, but only by adding another check in the middle of the loop to exit when EOF is reached -- in which case, the loop condition itself will never be used (i.e., the other check is the one that will actually do the job of exiting the loop).
What you normally do want to do is check for EOF as you read the data. Different functions indicate EOF in different ways. fgets signals failure (including EOF) by returning NULL. Most others (getc, fgetc, etc.) do return EOF, so you typically end up with something like this:
int ch; // Note, this should be int, NOT char
while (EOF != (ch=getc(pFile)))
process(ch);
or:
char buffer[MAX_LINE_SIZE];
while (fgets(buffer, sizeof(buffer), pFile))
process(buffer);
With scanf, checking for success is a little more complex -- it returns the number of successful conversions, so you want to make sure that matches what you expected. For example:
while (1 == fscanf(fPfile, "%d", &input_number))
process(input_number);
In this case I've used 1 because I specified 1 conversion in the format string. It's also possible, however, for conversion to fail for reasons other than EOF, so if this failes, you'll frequently want to check feof(pFile). If it returns false, do something like reading the remainder of the line, showing it to the user in a warning message, and then continuing to read the rest of the file.
It depends what pFile and EOF are defined as, but I will asssume that pFile is a *FILE, and EOF is from stdio.h. Then I guess you should do something like:
#include <stdlib.h>
#include <stdio.h>
#define FILENAME "file.txt"
int main(void) {
FILE *pFile;
int ch;
pFile = fopen(FILENAME,"r");
if (pFile) {
while ((ch = getc(pFile)) != EOF) {
printf("Read one character: %c\n", ch);
}
close(pFile);
return EXIT_SUCCESS;
} else {
printf("Unable to open file: '%s'\n", FILENAME);
return EXIT_FAILURE;
}
}
which yields
$ echo "abc" > file.txt
$ /tmp/fileread
Read one character: a
Read one character: b
Read one character: c
Read one character:
# last character being a linefeed
Assuming pFile is your file handle, this doesn't change as you read from the file. EOF is returned by e.g. fgetc(). See e.g. http://www.drpaulcarter.com/cs/common-c-errors.php#4.2 for common ways to solve this.
here is correct way:
c = getc(pFile);
while (c != EOF) {
/* Echo the file to stdout */
putchar(c);
c = getc(pFile);
}
if (feof(pFile))
puts("End of file was reached.");
else if (ferror(pFile))
puts("There was an error reading from the stream.");
else
/*NOTREACHED*/
puts("getc() failed in a non-conforming way.");
fclose(pFile);
pFile is a pointer to a file. EOF is usually defined as -1, a signed integer.
What you should do is fopen, make sure pFile != NULL, then call some function on the file handle until that function returns EOF. A pointer will (or rather, should) never be EOF. But a function acting on that pointer may return EOF.
I'm guessing you want to keep looping while you haven't hit end-of-file. In that case, you are looking for this:
while (!feof(pFile))
{
...
}
That said, this is still not quite correct. feof will only return true once it tries to read beyond the end of the file. This means feof can return false and yet there is no more data to read. You should really try your operation and only check for end of file if it fails:
char buffer[SIZE];
while (fgets(buffer, sizeof(buffer), pFile))
{
...
}
if (!feof(pFile))
{
// fgets failed for some reason *other* then end-of-file
}