I am trying read a text from file in C but I am getting nothing in command prompt.Here my code is,please help me ...
#include <stdio.h>
#include <stdlib.h>
int main(void) {
FILE *file=NULL;
file = fopen("C:\\Users\\ylmzt_000\\Desktop\\Yeni klasör\\deneme.txt", "r");
if(file != NULL)
{
printf("----------------\n");
printf("content\n");
printf("-----------------\n");
int ch;
while((ch=fgetc(file)) != EOF)
{
putchar(ch);
}
printf("\n");
fclose(file);
}
return 0;
}
If fopen() returns NULL, an error occured. Construct an else part which may contain
fprintf(stderr, "cannot open '%s' (%s)\n", fn, strerror(errno));
where fn contains your filename.
Also see http://linux.die.net/man/3/fopen for further hints.
There is no obvious problem in your code. The problem may be related to the fact that the filename contains non-ASCII characters:
C:\\Users\\ylmzt_000\\Desktop\\Yeni klasör\\deneme.txt
Try renaming the directory with only ASCII characters.
Related
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).
I'm trying to write a program that reads a text file, using C with Visual Studio.
This is my current code (which doesn't work):
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *filePTR;
char fileRow[100];
filePTR = fopen_s(&filePTR, "text.txt", "r");
// Opens the file
if(filePTR){
while(!feof(filePTR)) {
// Reads file row
fgets(fileRow, 100, filePTR);
// Displays file row
printf("%s \n", fileRow);
}
printf("\nEnd of file.");
}
else {
printf("ERROR! Impossible to read the file.");
}
// Closes the file
fclose(filePTR);
return 0;
}
I'm getting the following warning:
'filePTR' may be '0': this condition does not meet the function specification 'fclose'.
What am I doing wrong? I haven't been programming in C since a while ...
The problems begin long before the fclose. This line is incorrect:
filePTR = fopen_s(&filePTR, "text.txt", "r");
It overwites the file pointer already assigned by passing a pointer as the function argument &filePTR.
The function returns an error status, not the file pointer. Please see the man page:
Return Value Zero if successful; an error code on failure.
Also, please see Why is while ( !feof (file) ) always wrong?
I suggest this:
#include <stdio.h>
#include <stdlib.h>
int main(void) { // correct definition
FILE *filePTR;
char fileRow[100];
if(fopen_s(&filePTR, "text.txt", "r") == 0) {
while(fgets(fileRow, sizeof fileRow, filePTR) != NULL) {
printf("%s", fileRow); // the string already contains a newline
}
fclose(filePTR); // only close if it was opened
printf("\nEnd of file.");
}
else {
printf("ERROR! Impossible to read the file.");
}
return 0;
}
Note that I moved the fclose call up. You can't close a file that you did not open.
TODO: If a certain word exists in the .txt file, copy that word to another txt file
PROBLEM: It won't write the word after it is found in "from.txt" to "to.txt".
ERROR:
This line: while ((fscanf(ifp, "%s", line)) != EOF)
CODE:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
#define MAX_LINE 256
void main()
{
FILE *ifp;
FILE *ofp;
char line[MAX_LINE];
char word[MAX_LINE];
if ((ifp = open("from.txt", "r")) == NULL)
{
printf("Can't open input file.");
exit(1);
}
if ((ofp = open("to.txt", "w")) == NULL)
{
printf("Can't open output file.");
exit(1);
}
printf("Enter your word: ");
gets(word);
while ((fscanf(ifp, "%s", line)) != EOF)
{
if (strcmp(line, word) == 0)
{
fputs(line, ofp);
break;
}
}
fclose(ifp);
fclose(ofp);
getch();
}
You are using a wrong API for opening a file. API which you use -- open -- is for low-level, descriptor based access. You'll get an int value out of it, and ifp and ofp won't be correct.
You must use a stream based API, called fopen. It returns a pointer to the FILE structure, which in turn you can pass to fscanf() etc.
Very important: compile this program with all compiler warnings and observe the output. I'm pretty sure you're getting a log of warning messages from the compiler already.
PROBLEM: It won't write the word after it is found in "from.txt" to "to.txt".
As noted in comments and other answers, and for other reasons, open() may not be the best choice for writing strictly ANSI portable code.
But this is not the reason for the stated problem.
The function strcmp(...) is not doing what is needed.
In this line:
if (strcmp(line, word) == 0)
A single word is being compared with the entire line. And the single word is never identified. Even if the line in the file appears to have only a single word, white space, such as a space, tab or new line character ( " ". \n, \t) would cause the two arguments of strcmp to be unequal.
strcmp(string1, string2) possible return values are:
Positive integer when string1 is greater than string2
Zero when string1 is equal to string2
Negative integer when string1 is less than string2
The function strstr would be a better fit. Change the strcmp line to use strstr :
if (strstr(line, word)){...
strstr(...) looks for the existence of a sub-string within a string. And, with the other changes that have been discussed, made your code do as you described it should.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
#define MAX_LINE 256
void main()
{
FILE *ifp;
FILE *ofp;
char line[MAX_LINE];
char word[MAX_LINE];
//**************************************************************** it's fopen not open ***********************************************************
if ((ifp = fopen("from.txt", "r")) == NULL)
{
printf("Can't open input file.");
exit(1);
}
if ((ofp = fopen("to.txt", "w")) == NULL)
{
printf("Can't open output file.");
exit(1);
}
printf("Enter your word: ");
gets(word);
while ((fscanf(ifp, "%s", line)) != EOF)
{
if (strcmp(line, word) == 0)
{
fputs(line, ofp);
break;
}
}
fclose(ifp);
fclose(ofp);
getch();
}
its working fine ...
Hello all I'm trying to read a large txt file, word by word, then print each word out then continue on with the loop until EOF but I got no output after running this code. I check everything, file name was correct, the file also in the same folder with my c file. Could anyone please explain what is going on? Thank you. Here is the txt file, and the code:
.txt file
#include <stdio.h>
#include <string.h>
int main(void) {
FILE *infile;
char temp_1[25];
setvbuf(stdout, NULL, _IONBF, 0);
infile = fopen("LittleRegiment.txt", "r");
if(infile != NULL) {
while(fscanf(infile, "%s", temp_1) != EOF) {
printf("%s ", temp_1);
}
} else {
printf("Couldn't open the file.");
}
return 0;
}
Try printing the reason for the error.
} else {
//printf("Couldn't open the file.");
perror("open file"); // prototype in <stdio.h>
}
I created a function to print the contents of a file:
void readFile(char* filename)
{
int c ;
file = fopen(filename, "r");
printf("The contents of the file are:\n");
while((c = fgetc(file)) != EOF)
{
printf("%c", c);
}
return;
}
where file is a global variable. GDB gives output as follows:
_IO_getc (fp=0x0) at getc.c:39
39 getc.c: No such file or directory.
(gdb) bt
#0 _IO_getc (fp=0x0) at getc.c:39
#1 0x000000000040075e in readFile ()
#2 0x00000000004006d4 in main ()
However, the file is present and I get the SEGFAULT after printing the contents of the file. It might be because the buffer here (c) is small but I am not sure. Also, I don't know how do I fix this even if that were the case. Can anyone suggest how do I proceed?
EDIT
I call the readFile function only once. Here is my calling function:
int main(int argc, char* argv[])
{
char * filename;
filename = argv[1];
readFile(filename);
printf("File Handler: %ld", (long)file);
fclose(file);
return 0;
}
You're passing in a filename that doesn't exist or for some other reason cannot be opened. Get rid of the segfault by checking for errors (you'll need to #include <errno.h> and <string.h> too for this:
void readFile(char* filename)
{
int c ;
file = fopen(filename, "r");
if (file == NULL) {
printf("Cannot open file '%s' : %s\n", filename, strerror(errno));
return;
}
printf("The contents of the file are:\n");
while((c = fgetc(file)) != EOF)
{
printf("%c", c);
}
return;
}
Most likely your file is NULL and you are still trying to read it.
I simulated this behaviour (SEG fault) when I deleted this file.
If file exists then your code works fine.
Check what path you are passing.. If you are using single \ try with \\ and see if this works. First \ will work as escape sequence and final path will be send as D:\temp\use.dat to fopen.
readFile("D:\\temp\\user.dat");
Before you do anything with a file, you must ensure that you opened it successfully. This is done by checking that the file pointer received by calling fopen is not NULL.
Once you do this, you read using whatever function you choose until it returns a value that indicates failure to read — a NULL pointer for fgets, 0 or EOF for fscanf, or EOF for fgetc.
In any case, you challenge these return values in two ways. The first way is to check for read errors using ferror. The other way is to check whether the end of the file was reached using feof.
A complete program that should work, based upon your code:
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
enum { OPEN_ERROR = 1, READ_ERROR };
enum { PARAM_EXIT = 1, OPEN_EXIT, READ_EXIT };
FILE *file = NULL;
int readFile(char* filename)
{
int c;
file = fopen(filename, "r");
if (file == NULL)
return OPEN_ERROR;
printf("The contents of file '%s' are:\n", filename);
while((c = fgetc(file)) != EOF)
printf("%c", c);
/*
* fgetc returns EOF on end of file and when an error occurs.
* feof is used to determine whether the end of the file was reached.
* Otherwise, we encountered a read error.
*/
if (feof(file))
c = 0;
else
c = READ_ERROR;
return c;
}
int main(int argc, char *argv[])
{
int status = 0;
if (argc == 1) {
fprintf(stderr, "usage: %s file\n", argv[0]);
return PARAM_ERROR;
}
/* Check that <program ""> wasn't used... */
if (argv[1][0] == '\0') {
fprintf(stderr, "error: empty filename detected, exiting. . .\n");
return PARAM_ERROR;
}
switch (readFile(argv[1])) {
case 0:
break;
case OPEN_ERROR:
fprintf(stderr, "error: file open failed - %s\n", strerror(errno));
status = OPEN_EXIT;
break;
case READ_ERROR:
fprintf(stderr, "error: file read failed - %s\n", strerror(errno));
status = READ_EXIT;
break;
default:
fprintf(stderr, "error: unknown error occurred, aborting...\n");
abort();
}
if (file != NULL)
fclose(file);
return status;
}
Of course, normally you would close the file in the same function in which it was opened (e.g. something like filep = openFile(...); readFile(filep); fclose(filep);, except error handling would be used of course).
I am completely changing my answer
Actually, the file that I was reading was open in gedit (which might explain why I was getting "NULL" even after printing the file contents. I closed the file and removed my NULL comparison code and it works perfectly fine.
Ok, from everybody's comments I got to know that you basically get a SEGFAULT when you read the contents of file that has NULL contents. I just made a simple fix in my while loop:
while((c != EOF))
{
printf("%c", c);
c = fgetc(file);
if(c == NULL)
break;
}
Problemo solved! (Although, the compiler gives me a warning of "comparison between pointer and integer".)