Cannot print characters from a file - c

I am trying to read a file character by character and print it on screen.
However, the character is not displaying, I am getting a box with 0001 in it.
This is my code
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp;
int ch;
fp=fopen("myfile.txt", "rb");
while((ch = getc(fp)) !=EOF){
putc(ch, stdout);
}
fclose(fp);
return 1;
}

you need to check the return values from fopen, to ensure you opened the file successfully, you could be executing from the wrong directory.
Plus if your file is a TEXT file, you should be opening using "rt".

Basic File Opening modes in C is
"r"-reading
"w"-writing
"a"-append
"r+"-reading+writing
"w+"-reading+writing
"a+"-"reading+appending"
This code is enough to read .txt files
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp;
int ch;
fp=fopen("myfile.txt", "r");
while((ch = getc(fp)) !=EOF){
putc(ch, stdout);
}
fclose(fp);
return 0;
}

Related

how to print the content of a text file in c

Iam trying to print the content of a text file called text.txt in the terminal in c I have the following code but it doesn't work:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main(){
char str[255];
FILE *fp;
fp = fopen("text.txt","r");
while (fgets(str,255,fp)!=NULL){
printf("%s",str);
fclose(fp);
};
}
I couldn't find a solution please help
First of all, you are closing the file inside the loop. fclose should lie at the end of your program. Secondly, fopen() might fail (you don't have permission to read the file for example). So, don't forget to handle that too.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main(){
const int sz = 255;
char str[sz];
FILE *fp;
fp = fopen("input.txt","r");
if(fp == NULL){
// opening the file failed ... handle it
}
while (fgets(str,sz,fp)!=NULL){
printf("%s",str);
};
fclose(fp);
}
Here is another similar way
if (fp!=NULL)
{
// file open succeded. do sth with it.
fclose (fp);
}
Hope this helps and keep coding!

Counting words in a file using only stdio.h and stdlib.h

I need to count the number of WORD/CHARACTERS "ananas" in some FILE.
I need to rewrite this file with the number of words "ananas".
Also I can use only these 4 functions!!!! fopen(), fclose(), fgetc(), fputc()
It should be count Big Capitals characters as Smaller characters too (e.g. aNaNAs)
Example
Input file: Bananas are edible fruits, botanically berries. I love BANANAS because they are really good aNanas.
Output file: 3
My code:
#include <stdio.h>
#include <stdlib.h>
int main(){
char filename[20];
char ch;
FILE *fp = fopen(filename,"r");
if (fp == NULL)
{
perror("Error opening file.");//perror=printf pre errory
return 1;
}
/* Normal processing continues here. */
while((ch = fgetc(fp)) != EOF){
}
fclose(fp);
return EXIT_SUCCESS;
}

Changing the periods in my file to exclamation points, and saving the full text to a new file

In a file I made, practice.txt, I have a few sentences that end with (.), I want to rewrite everything to a different file, but change all the periods to exclamation points.
#include <stdlib.h>
#include <stdio.h>
int main() {
FILE *fp = fopen("practice.txt", "r");
FILE *fp2 = fopen("practice_!.txt", "w");
if (fp == NULL)
return -1;
int c;
while ((c = fgetc(fp)) != EOF) {
if (c == '.') {
c = '!';
}
fputc(c, fp2);
}
fclose(fp);
fclose(fp2);
return 0;
}
This code doesn't seem to be outputting anything to the new file.
You should test if both files wre open successfully and output a meaningful message if not. If your program fails to open the input file, it creates or truncates the output file and exits silently. This might explain be what you observe. Are you sure you run the program from the directory where the input file was created?
The copying and substitution code seems OK.
Here is a modified version:
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
FILE *fp = fopen("practice.txt", "r");
if (fp == NULL) {
fprintf(stderr, "cannot open %s: %s\n",
"practice.txt", strerror(errno));
return 1;
}
FILE *fp2 = fopen("practice_!.txt", "w");
if (fp2 == NULL) {
fprintf(stderr, "cannot open %s: %s\n",
"practice_!.txt", strerror(errno));
return 1;
}
int c;
while ((c = fgetc(fp)) != EOF) {
if (c == '.') {
c = '!';
}
fputc(c, fp2);
}
fclose(fp);
fclose(fp2);
return 0;
}
The Un*x way to write that program, is a filter (basically a program that reads from stdin and writes to stdout)
#include <stdio.h>
int main(void) {
int c;
while ((c = getchar()) != EOF) {
if (c == '.') c = '!';
putchar(c);
}
return 0;
}
and you'd use it as
executable <practice.txt >practice_!.txt
You code is correct.
If the file was not opened, you'd get a segmentation fault since either fp or fp2 would then be NULL.
So... the only thing I can think of is that you're hunting a red herring.
Possibilities that come to mind:
you're actually executing an old version of the executable file.
you're on a Unix console (e.g. Linux), and you did not escape the "!" which is a shell special character. For example I managed to get this just now on my bash:
$ cat practice_!.txt # I should have enclosed the name in single quotes
cat practice_.txt
cat: practice_.txt: No such file or directory
(The file "practice_!.txt" does exist; "practice_.txt" does not).

Error accured in reading files by using line by line in c

log.txt :
Hello world
world is not enough
to show our knowledge
cpp file :
#include <stdio.h>
#include <string.h>
int main()
{
char szLine[512+1]={0};
FILE *fp=fopen("log.txt", "r");
while(!feof(fp))
{
fscanf(fp, "%512[^\n]", szLine);
puts(szLine);
getchar();
}
return 0;
}
Acually expected output for this program has to read line by line. But it read only first line alone. What is the mistake on this code. thanks advance.
you can change your program like this:
#include <stdio.h>
#include <string.h>
int main()
{
char szLine[512+1]={0};
FILE *fp=fopen("log.txt", "r");
while(!feof(fp))
{
fgets(szLine,512,fp);
puts(szLine);
getchar();
}
return 0;
}
because the offset of the file stream always be 0, so you read
"%512[^\n]" does not read the endline character. The remaining part of the file starts with \n and fscanf fails to read the line(it return 0 instead of 1). You need to read the endline character !
#include <stdio.h>
#include <string.h>
int main()
{
int bla;
char szLine[512+1]={0};
FILE *fp=fopen("log.txt", "r");
while(!feof(fp))
{
bla= fscanf(fp, "%512[^\n]", szLine);
if(bla==1){
printf("%d\n",bla);
puts(szLine);
getchar();
fgetc(fp);
}
}
return 0;
}
Using getline() may be a more reliable solution.
getline(&szLine,&size,fp);
Bye,
Francis
try this
while(fscanf(fp, " %512[^\n]", szLine)==1)
{
puts(szLine);
getchar();
}

How to create a file for use in c?

I have a program:
#include <stdio.h>
#include <string.h>
// ne menuvaj ovde
void wtf() {
FILE *f = fopen("text.txt", "w");
char c;
while((c = getchar()) != EOF) {
fputc(c, f);
}
fclose(f);
}
int main() {
wtf();
FILE *vlezna;
vlezna=fopen("text.txt","r");
float words=0,lines=0,average=0;
int counter=0;
char ch;
while((ch=fgetc(vlezna))!=EOF)
{
if(ch==' ')
words++;
if(ch=='\n');
{
words++;lines++;
}
}
average=words/lines;
printf("%f",average);
fclose(vlezna);
vlezna=fopen("text.txt","r");
while((ch=fgetc(vlezna))!=EOF)
{ words=0;
if(ch==' ')
words++;
if(ch=='\n')
{
words++;
if(words<average) counter++;
}
}
fclose(vlezna);
printf("%d",counter);
}
So i presume the first function writes to the file. But i guess the file should be created first, and i don't know how(except with right click new text document).
Also i didn't know how to return the pointer at the beginning of the file so i closed it and opened it again presuming that that will return the pointer at the beginning?
fopen create the file if it does not exist if option is "w".
Read the documentation here : http://www.cplusplus.com/reference/cstdio/fopen/
There is no need to create. For the man page of fopen:
``w'' Truncate to zero length or create text file for writing. The stream is positioned at the
beginning of the file.
To set the file pointer use fseek. However, to read and write you need different open flags.

Resources