I am trying to read from a file in C using fgets() however I have run into the following problem:
Although I can open the file successfully using fopen():
if ( file=fopen(filename, "r") == NULL )
{
printf("Couldn't open specified file. Please try again.");
exit(1);
}
I can't read anything from it. I am using the following loop, although nothing is printed and the execution terminates successfully.
while ( (fgets(inputLine, 1023, file)) != NULL)
{
printf("Hello world");
}
This is independent of the actual filename, filesize or file contents. Nothing seems to work and nothing is shown up as an error in the debugger. A sample file I have tried is the following directly copied and pasted:
test.txt
#include <stdio.h>
int main ()
{
printf("Hello World");
}
Do you have any guess as to why this is happening?
NOTE: I have taken the loop code from this S'O question so I guess it's right.
This is incorrect:
if ( file=fopen(filename, "r") == NULL )
Try:
if ( (file=fopen(filename, "r")) == NULL )
They way you have written it is equivalent to file = 0 (assuming the file is succesfully opened. If not, it is the same as file = 1). This is not what you want.
Apart from the fact you are doing a mistake in the condition of fopen, there is also a potential problem with snippets such as:
while ( (fgets(inputLine, 1023, file)) != NULL)
{
printf("Hello world");
}
By default, the standard output stream stdout is line-buffered. This means that you should add a \n or a call to fflush to force the data to being effictively written.
fflush(stdout);
Related
It's my first exercise about Files and I have to write some code so that if I write a word in the console, it gets printed in the file. The program ends if I input the word "fine" (it's Italian for end). It seems like the file is opened and closed correctly, the program reads the inserted chars, but nonetheless, the file remains blank.
I tried opening the file in various modes, I tried printing how many chars were read, I even tried deleting the file (but it actually does't exit even if I added exit(1).
#define _CRT_SECURE_NO_DEPRECATE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
int main() {
FILE * fp;
char s[64];
if ((fp = fopen("prova.txt", "r+")) == NULL) {
printf("Error.\n");
exit(1);
}
do {
scanf("%s", s);
if (strcmp("fine", s) != 0) {
fprintf(fp, "%s ", s);
}
} while (strcmp("fine", s) != 0);
fclose (fp);
return 0;
}
It should save all the words in a text file, but it remains blank.
Your program looks OK. Most likely, you are checking the wrong file.
An educated guess: you are using some IDE. If this is the case, the file is created, but is created somewhere else. To be sure, print the working directory (man getcwd) somewhere in the beginning of your program, and look for the file there.
you have to use "w" to open a new file with write priviledges
change
if ((fp = fopen("prova.txt", "r+")) == NULL) {
with
if ((fp = fopen("prova.txt", "w+")) == NULL) {
EDIT: Maybe i didn't explained myself, r+ will fail if the file doesn't exist, changing it works for me
So I've been trying to experiement with some decryption algorithms and ciphers and tried to do some of them on my own. At them moment I'm writing in C an affine algorithm which I am trying to decrypt a line from a .txt file which I decrypted myself so here's where I think my problem appears since my code always pops text file corrupted and doesn't proceed to the next task.
file = fopen("encr_affine.txt", "r");
if(file)
{
while ((c = getc(file)) != EOF)
putchar(c);
fclose(file);
}
fgets(str,100,file);
if ( fgets(str,100,file) == NULL )
{
fprintf(stderr, "Text file corrupted\n");
return -1;
}
What is the mistake here? Is it reading the whole line of the txt file or just the first char? And why it doesn't proceed on into the next tasks?
Thank you in advance
It always prints your Text file corrupted message because the file is always closed (or never open) when it gets there.
Look what this first part does:
file = fopen("encr_affine.txt", "r");
if(file)
{
while ((c = getc(file)) != EOF)
putchar(c);
fclose(file);
}
It opens the file, then (if it's really open), it reads the entire file, byte by byte, then prints it all to stdout. It then closes the file.
Then you try to do stuff on a closed file:
fgets(str,100,file);
This would do nothing because the file is closed, and would return NULL. If the file were never opened, it would still return NULL due to an error.
But then you try it again:
if ( fgets(str,100,file) == NULL )
{
fprintf(stderr, "Text file corrupted\n");
return -1;
}
This fgets(str,100,file) always returns NULL because once again the file is closed.
Perhaps what you really want to do is to process the bytes one at a time in your first loop before printing them with putchar().
#include<stdio.h>
int main()
{
FILE *opening;
opening = fopen("hello.usr","w");
fprintf(opening,"Hello world!");
fclose(opening);
printf("Writing to the file was successful.\n");
printf("Closing the program");
return 0;
}
I have tried this code to create a file in c programming and write the text "Hello world!" in it. What's wrong with this code?
If you want to know what is wrong check the result of fopen
opening = fopen("hello.usr","w");
if (opening == NULL) {
perror("fopen");
}
As of now, you don't know whether you managed to write to the file or not, so here's a suggestion which checks for it.
FILE *opening;
opening = fopen("hello.usr", "w");
if (opening == NULL){
perror("fopen");
return 0;
}
By returning 0 here you remove the option for segmentation fault as the code will still try to write to the file even if it doesn't exist.
The error message you are getting most certainly is NOT produced by a compiler. It looks to me as a message of some automatic checker that tests correctness of the submited solutions.
Make sure that the output matches exactly the required one.
The message:
Your program's output is shorter than the expected
may indicate that there is something wrong with new line characters ('\n'). Check for those.
For example if the required output is:
Writing to the file was successful. Closing the program.
... printed in one line, your output obviously doesn't match as it has a new line after the first sentence. And if the checker testes for the first occurrence of a new line character it sees only
Writing to the file was successful.
which could be one of many possible explanations. If this is the case try simply:
#include<stdio.h>
int main()
{
FILE *opening;
opening = fopen("hello.usr","w");
fprintf(opening,"Hello world!");
fclose(opening);
// printf("Writing to the file was successful.\n");
// printf("Closing the program");
printf("Writing to the file was successful. Closing the program\n");
return 0;
}
Note also that this sort of error messages (in automatic testing environments) are usually triggered by ommited, added extra or confused non-printable characters (spaces, tabs, new lines) or punctuation marks which is hard to notice.
You may also want to check in this respect the text you print to the file.
Try to Instead "w" use "wt" in fopen
Try the following
#include <stdio.h>
int main() {
FILE *opening = fopen("hello.usr", "w");
if(opening == NULL){
printf("An error occurred when opening the file!");
return 0;
}
else{
fprintf(opening, "Hello world!\n");
fclose(opening);
printf("Writing to the file was successful.\nClosing the program.\n");
}
return 0;
}
I'm writing an application which should read some data at some level from a file. When I run the code (including fopen() and fclose())for more than a few hundred times, I got the error message (which I know it means that it cannot open the file):
Debug Assertaion Failed!
Program:
D:\blahblah
file: f:\dd\vctools\crt\crtwin32\stdio\fgets.c
Line: 57
Expression: (string!=NULL)
Can you please help me to understand why it should break after more than three hundered time?
Func_Main(char * filePath, ...){
for(int i=0;i<1000;i++){
Func_1(filePath);
....
}
....
}
Func_1(char* filepath){
char buffer[1024];
FILE * file= NULL;
file = fopen(filepath, "r");
while(fgets(buffer, sizeof(buffer), file)){
\\ do something
}
fclose(file);
}
You should check the return value of fopen. It will return a null pointer if opening the file failed.
And it will fail because \ is an escape character , use \\ in the filename string.
Problems I see:
You never use the argument passed to Func_1. You use a hard coded path instead.
The hard coded path has an error. You are not escaping the backslash in the hard coded path . It should be:
file = fopen("c:\\blahblah.txt", "r");
^^
You are not checking whether fopen was successful. You are assuming it was successful. Use:
file = fopen("c:\\blahblah.txt", "r");
if ( file == NULL )
{
// Deal with the error.
perror("Unable to open the file");
}
Update, after the OP edited the question
The first two points can be ignored. The last point still needs to be considered.
file = fopen(filepath, "r");
if ( file == NULL )
{
// Deal with the error.
perror("Unable to open the file");
}
The program always ends up exiting. I seem to be running in to this problem frequently and I think I somehow previously fixed it but I'm not sure how. Why does it not create a file?
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
int main (void){
FILE *fp;
int c;
char file_w[100];
char string[100];
printf("Enter filename\n");
fgets(file_w, 100, stdin);
fp = fopen(file_w, "w");
if (fp == NULL){
printf("Can't open file\n");
exit(0);
}
printf("Enter a string");
fgets(string, 100, stdin);
for(c = 0; c <= sizeof(string); c++)
{
fprintf(fp, "%s\n", string);
}
printf("file written");
fclose(fp);
return 0;
}
Try to print the name of the file you have entered:
printf("%s\n", file_w);
just after the line you get file_w, just to be sure to enter what you want. I same cases the terminal could be wrongly configured.
Try to enter an absolute name path, if your computer is a Linux or Unix:
/tmp/newfile.txt
If your computer is Windows... Well try to see if C:\temp\ exist (or create it) and then enter:
C:\temp\newfile.txt
In any case, remember that you can specify an absolute path, and not only the file name. So double check if you have the rights (i.e. the permissions) to write into the directory where the file should be written.
In case you want check the error and have a better description of the problem try to use the following lines instead of your code, just under the fopen
if( fp == NULL ) {
// Error, as expected.
perror( "Error opening file" );
printf( "Error code opening file: %d\n", errno );
printf( "Error opening file: %s\n", strerror( errno ) );
exit(-1);
}
strerror it is a wonderful function just because return you a description of the problem instead of an error code.
I bet the problem is "invisible character after actual name from fgets()". I'll let you figure out exactly what that character is, where it comes from and how to fix it, as "struggling to solve a problem" is part of the learning process when it comes to programming. If it was easy, everyone could do it.
If the return value of fopen is NULL it means some error occurred. I suggest you look into the errno global to see what error has occurred to help you debug why it's not opening the file.
The w flag does the following:
write: Create an empty file for output operations. If a file with the same name already exists, its contents are discarded and the file is treated as a new empty file.
So it should create a file when none exists, or when it does exist, overwrite its content.
If it does not do that, you have another problem, but from the little information you've given, it's hard to tell what it is.
I tried as a name of file the following:
C:\\temp\\test_file.txt
or
fopen("C:\\temp\\employees.txt", "w");
and it works fine, without errors (I made it in Windows 10. GCC win32, Version: 6.3.0).
I think that you have to use an absolute path to create the file.
use gets() instead of fgets()...it will work
.
.
gets(file_w);
.
.