C programming: Reading from file and printing to console - c

Good evening,
I know there's similar questions, which I have been sifting through, but this particular issue seems to be unique.
I am attempting to figure out how to simply read a text file into a string, and then write the string to standard output. I tried this code, but nothing is happening in the console when I call puts(). The file.txt generates properly with "hello" written, but the last if statement doesn't seem to work for some reason since it does not reach my test condition. How can I make this functional?
This was the code given by many, many examples online, only slightly modified:
#include <stdio.h>
int main()
{
FILE *fp;
char str[60];
fp = fopen("file.txt","w+");
fprintf(fp,"%s","hello");
if(fp==NULL){
perror("Error opening file");
return(-1);
}
if (fgets (str, 60, fp)!=NULL)
puts(str);
printf("%s","test");
fclose(fp);
return 0;
}

By the time you call fgets(), the file pointer is already at end of file. Add a call to rewind(fp) before your fgets().
Oh, also when you're opening the file, put your check for fp==NULL before the call to fprintf().

After you have written the file, you have to fclose() the fp and re-fopen() the file for reading.

Related

Opening a file in c to read

At first I wanted to open a file and read its contents, in C, however, in doing so, I was unable to run the program without errors, I even tried to just open the file, and not read anything, I did exactly what I saw on other questions like this and got errors, here is the code.
#include <stdio.h>
void main(void){
FILE *file = NULL;
file = fopen('list.txt', 'r');
}
(Repeating BLUEPIXY's comment as an answer so search finds it)
Your mistake is that in 'list.txt', 'r' the ' does not mark a string in 'C' (unlike in python) you must use ".
The ' is used to specify `a single character variable.
First of all do you have a file called list.txt, and what if the program does not find list.txt. It can't read the file so you must check for exist file.
#include <stdio.h>
int main (void) {
FILE *file_exist = fopen("list.txt", "r");
if (file_exist) {
printf("File Founded");
//Insert what do you want to do with the file like fscanf? fgetc? Up to you
}
else {
printf("File Not Found");
//If there is no file, You can start ignore reading the file since will cause error dont know what to read
}
}
Here you can avoid error, while reading your file.

Reading from file in C using fread

I'm learning how to read content from a file in C. And I manage to scrape through the following code.
#include <stdio.h>
#include <stdlib.h>
void read_content(FILE *file) {
char *x = malloc(20);
// read first 20 char
int read = fread(x,sizeof(char),20,file);
if (read != 20) {
printf("Read could not happen\n");
}
else {
printf("the content read is %s",x);
}
free(x);
return;
}
int main(int argc,char *argv[]) {
FILE *fp;
fp = fopen("test.txt","w+");
read_content(fp);
fclose(fp);
return 0;
}
But for some reason (which I'm not able to understand) I see the read bytes count as 0.
The problem is that you open the file with the w+ mode. There are two possibilities:
if the file doesn't exist, it will be created empty. Reading from it immediately gives end of file resulting in fread() returning 0.
if the file does exist, it will be truncated i.e. changed into an empty file. Reading from it immediately gives end of file resulting in fread() returning 0.
If you just want to read from the file (as per your example), open it in mode r. If you want to read and write without destroying its existing content, use mode r+.
Whatever mode you choose, always check that fopen() returns non null and print the error if it returns null (this is not the cause of your problem but is best practice).
From Man Page w+ flag:
Open for reading and writing. The file is created if it does
not exist, otherwise it is truncated.
You are probably trying to open a file which doesn't exist at the path you provided, or is read-only as #WhozCraig suggested in comment. This means a new file is being created, an empty file! hence you are seeing 0 bytes read.
To sum up, The fopen is failing, in that case you need to check the return value if it is equal to -1.
To find what was the error, you can check the errno as it is set to
indicate the error.
If you are only intending to read, open the file with r flag instead of w+
The problem lies within this line of code:
fp = fopen("test.txt","w+")
the "w+" mode, clear the previous content of the file and the file will be empty when you just going to read the file without writing anything to it. Hence, it is printing "Read could not happen" because you are trying to read an empty file.
I would suggest you to use "r+" mode, if you are willing to read and then write into the file. Otherwise, r mode is good enough for simple reading of a file.

read operation without fseek in a+ mode causes extra white spaces in the file

When I executed below code, m2.txt created correctly as expected with the specified data.
#include <stdio.h>
int main()
{
FILE *fp1;
char ch;
fp1=fopen("m2.txt", "a+");
fputs("Hello, data is appended\0", fp1);
fseek(fp1,0,SEEK_SET);
while((ch=getc(fp1))!=EOF)
{
putc(ch,stdout);
}
fclose(fp1);
return 0;
}
Now I commented fseek and executed the below code. (I deleted this m2.txt file before executing)
#include <stdio.h>
int main()
{
FILE *fp1;
char ch;
fp1=fopen("m2.txt", "a+");
fputs("Hello, data is appended\0", fp1);
//fseek(fp1,0,SEEK_SET);
while((ch=getc(fp1))!=EOF)
{
putc(ch,stdout);
}
fclose(fp1);
return 0;
}
To my surprise, displayed data on the screen had just whitespaces. Even "Hello, data is appended"was missing. Also the m2.txt file had many white spaces.
Why this problem? If fseek is not done before read, it should affect only read operation I thought. Why extra spaces are getting written to the file?
In a+ mode, read pointer is pointing to the beginning if no write operation is done. But in case write operation is done, pointer will be at the end I suppose. In such case, read should not be displaying anything without fseek right? In anycase, issues could be there with read. But why write is having issues even though write is done before read.
I am using Codeblock 15.12 and default mingw came with codeblock.
Edited:
I further thought if it could be some compiler related issue. Grabbed old Visual Studio 6 and compiled. Several lines of unreadable characters are printed at the end. So it is not compiler issue. Somewhere some silly issue is there it looks.
After some search, I found that fflush() or fclose() or fseek() is needed before reading the file. Otherwise the entire write buffer may be filled/affected. Tried with fflush() and write operation did not write any junk at the end even if fseek() is not called. Here is the code (Of course fseek() will be there inplace of fflush() in actual code. I just commented fseek and added fflush() for testing purpose).
int main()
{
FILE *fp1;
char ch;
fp1=fopen("m2.txt", "a+");
fputs("Hello, data is appended", fp1);
fflush(fp1);
// fseek(fp1,0,SEEK_SET);
while((ch=getc(fp1))!=EOF)
{
putchar(ch);
}
fclose(fp1);
return (0);
}

C - fgets weird behaviour

It may be a stupid issue but its been a few hours I've been looking around to fix that and it drives me crazy.
That little code works perfectly fine if the fgets line is commentated (as provided).
As soon as I remove the comment the whole function will NOT do anything at all. My process jut freezes - even the printf before the fgets isnt executed.
void RetirerTransaction(char* filePath, char* transaction) {
FILE* f;
FILE* result;
char tempStr[128];
char line[100];
printf(">>%s<<",filePath); // Just to check everything is ok
strcpy(tempStr,"grep -v \"");
strcat(tempStr,transaction);
strcat(tempStr,"\"");
strcat(tempStr,filePath); // tempStr = grep -v "XXX" myfile
result = popen(tempStr, "r");
/*
if (fgets(line,100,result)) {
printf("OK");
}
*/
}
Thank you in advance.
You miss a space between the closing quote of the pattern and the file parameter for grep. That makes the whole thing including the filename be taken as the pattern.
By default, grep reads from standard input. It blocks trying to read from stdin because it doesn't have a file parameter.
Add the space like this and you'll be fine:
strcat(tempStr,"\" ");
Check the code below.Please add check for the popen return value. If popen fails and you are trying to do a fgets() then it might cause crash.
result = popen(tempStr, "r");
if(result == NULL)
return;
else
fgets(line,100,result);

Trouble testing copy file function in C

Okay so this is probably has an easy solution, but after a bit of searching and testing I remain confused.. :(
Here is a snippet of the code that I have written:
int main(int argc, char *argv[]){
int test;
test = copyTheFile("test.txt", "testdir");
if(test == 1)
printf("something went wrong");
if(test == 0)
printf("copydone");
return 0;
}
int copyTheFile(char *sourcePath, char *destinationPath){
FILE *fin = fopen(sourcePath, "r");
FILE *fout = fopen(destinationPath, "w");
if(fin != NULL && fout != NULL){
char buffer[10000];//change to real size using stat()
size_t read, write;
while((read = fread(buffer, 1, sizeof(buffer), fin)) > 0){
write = fwrite(buffer, 1, read, fout);
if(write != read)
return 1;
}//end of while
}// end of if
else{
printf("Something wrong getting the file\n");
return 0;}
if(fin != NULL)
fclose(fin);
if(fout != NULL)
fclose(fout);
return 0;
}
Some quick notes: I am very new to C, programming, and especially file I/O. I looked up the man pages of fopen, fread, and fwrite. After looking at some example code I came up with this. I was trying to just copy a simple text file, and then place it in the destination folder specified by destinationPath.
The folder I want to place the text file into is called testdir, and the file I want to copy is called test.txt.
The arguments I have attempted to use in the copyFile function are:
"test.txt" "testdir"
".../Desktop/project/test.txt" ".../Desktop/project/testdir"
"/Desktop/project/test.txt" "/Desktop/project/testdir"
I just get the print statement "Something wrong getting the file" with every attempt. I am thinking that it may be because 'testdir' is a folder not a file, but then how would I copy to a folder?
Sorry if this a really basic question, I am just having trouble so any advice would be awesome!
Also, if you wanted to be extra helpful, the "copyTheFile" function is supposed to copy the file regardless of format. So like if its a .jpg or something it should copy it. Let me know if any of you guys see a problem with it.
This is with ISO/POSIX/C89/C99 on Linux.
At the start, you'll want to include stdio.h to provide FILE and the I/O function declarations:
#include <stdio.h>
Aside from this, your program compiles and works properly for me. Unfortunately you can't copy to a directory without using stat() to detect if the destination is a directory, and if so, appending a file name before opening the file.
Some other minor suggestions:
A buffer with a power of two bytes such as 4096 is probably more efficient due to it lining up with filesystem and disk access patterns
Conventionally, C functions that return a status code use 0 for success and other values such as 1 for failure, so swapping your return values may be less confusing
When a standard library function such as fopen, fread or fwrite fails, it is a good idea to use perror(NULL); or perror("error prefix"); to report it, which may look something like:
$ ./a.out
...
error prefix: No such file or directory
if you are trying to write a new file in a directory, you should be giving the full path of the file to be written. in your case
"C:...\Desktop\project\testdir\testfile"

Resources