Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
Below is a simple code that I'm hoping SIZE.txt to be created, then be closed. It compiles without error, nor warning, but file wouldn't be created. However, a segmentation fault is thrown when code is executed.
Thanks for your kind help in advance.
#include "stdio.h"
void main() {
FILE *fp;
fp = fopen("SIZE.txt", "r+");
fclose(fp);
return;
}
The primary reason for the failure was due to the specification of the file mode as "r+" which will only open existing files, not create new files. A file is only created if "w+", "a", or "a+" is specified as the file mode.
check this, if file exists it will be display file already exist, but if the file doesn't exist it will be create it, depend what are you going to do, the ab+ you can just change to w
FILE *fp;
fp = fopen("SIZE.txt", "r");
if(fp==NULL){
fp=fopen("SIZE.txt", "ab+");
printf("File was created\n");
}
else{
printf("File already exists\n");
}
fclose(fp);
return 0;
Change:
#include "stdio.h"
To
#include <stdio.h>
Also, check for a NULL pointer being returned by fopen():
if ((fp = fopen("file.txt", "r")) == NULL) {
// Handle error...
}
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I am writing a program that reads a string and writes that string in another file which has not been created.
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
char s[50];
FILE *fp;
fp = fopen("E:\\poem.txt","w");
if(fp = NULL)
{
printf("Cannot open file");
exit(1);
}
printf("Enter a string\n");
while(strlen(gets(s))>0)
{
fputs(s,fp);
fputs("\n",fp);
}
fclose(fp);
return 0;
}
Since the "w" mode creates a new file if file is not already created,my program creates that file however it is unable to write it to the file
The double slash in fp = fopen("E:\\poem.txt","w"); is because i thought \p cannot be a escape sequence but i want to go to the directory E:\ so i used double slash.
However I even tried fp = fopen("poem.txt","w"); same thing happen creates a file but doesnot write on it.
Also checked this question but was not helpful C: can't write data on file
From man page of gets():
gets() returns s on success, and NULL on error or when end of file
occurs while no characters have been read.
When gets() return NULL (on failure), then strlen(NULL) causes segmentation fault.
So, you can simply use while(gets(s)!=NULL) instead of while(strlen(gets(s)) > 0)
As you mentioned in comment a typo use== instead of =
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char s[50];
FILE *fp;
fp = fopen("E:\\poem.txt", "w");
if (fp == NULL)
{
printf("Cannot open file");
exit(1);
}
printf("Enter a string\n");
while (strlen(gets(s)) > 0)
{
fputs(s, fp);
fputs("\n", fp);
}
fclose(fp);
return 0;
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I want to read file with C program here is the code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE * fptr;
fptr = fopen("text.txt","r");
char arr[150];
char c;
int i;
while(!feof(fptr) && i<5)
{
printf("%d\n",i++);
fgets(arr,150,fptr);
puts(arr);
}
fclose(fptr);
return 0;
}
When executed the program wont stop and the characters printed are weird, i dont know what is going wrong ?
The part causing error in your program is :
while(!feof(fptr))
Better read : What is wrong with "while(!feof(fptr))" and Why it's bad to use feof() to control a loop
A simple program to read is below which checks if file is opened or not. It's a good practice to check if file you are to perform operations on is opened or not.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char ch;
FILE *fp;
fp = fopen("text.txt", "r"); // read mode
if (fp == NULL) //Checking if file is open
{
perror("Error while opening the file.\n");
exit(EXIT_FAILURE);
}
printf("The contents of %s file are:\n", file_name);
while((ch = fgetc(fp)) != EOF){
printf("%c", ch); //Avoided creating a buffer
}
fclose(fp);
return 0;
}
#Though not so much realevant!!
I think the easiest way to read/write from/to file is using freopen() function. You can use scanf() & printf() in case of C and cin & cout in case C++ to read or write from file with this function.
Read from file: freopen("input.txt","r",stdin); where input.txt is filename.
Write to file: freopen("output.txt","w",stdout); no need to create output.txt your own. The file is automatically created when the program is executed.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I'm trying to use the fseek() and ftell() function to find the length of the file 'test.txt' which is present in the same directory as the file 'file.c'.
file.c
#include <stdio.h>
int main()
{
FILE *fp;
int len;
fp = fopen("test.txt", "r");
if(fp == NULL)
printf("Error opening file.");
fseek(fp, 0, SEEK_END);
len = ftell(fp);
fclose(fp);
printf("The size of the file test.txt is: %d.\n", len);
return 0;
}
test.txt
abc def
There is no problem when I compile the file, but when I try to run it, I'm getting the 'Segmentation fault (core dumped)' error and the execution terminates.
I'm trying to run this on a standard user in the Ubuntu environment.
You may be wondering why you did not see the printf statement before the 'Segmentation fault' occurred.
This is due to stream buffering of stdout. You either have fflush(stdout) or print a newline "\n" to prevent the output from being buffered.
In this case, 'Segmentation fault' has occurred before the buffer is flushed and printed.
So you can try either this:
printf("Error opening file.");
fflush(stdout);
or this:
printf("Error opening file.\n");
And of course, do not do anything more with the file pointer if it is NULL.
Actually, you'll better use perror(3) instead of printf for such error handling (if you insist on printf, show somehow the errno(3), perhaps as strerror(errno); see also strerror(3)). So we suggest:
if(fp == NULL) {
perror ("fopen test.txt");
exit (EXIT_FAILURE);
}
You don't need super user permission here. You are trying to open a file in read only mode. If the file is not existing then fopen() fails. Even if the file is not present you are trying to get the length of the file.
So you can try this:
#include <stdio.h>
int main()
{
FILE *fp;
int len;
fp = fopen("test.txt", "r");
if(fp == NULL){
printf("Error opening file.\n");
}else{
fseek(fp, 0, SEEK_END);
len = ftell(fp);
fclose(fp);
printf("The size of the file test.txt is: %d.\n", len);
}
return 0;
}
The problem with your code is probably test.txt is missing on the specified location and you are trying to open it. Even though open fails you are trying to get the length of the file which causes segmentation fault.
You don't need to open the file to check the length, and doing so increases the risk of failure because of lacking permission, etc.
If you want to check the length of a file (rather than figure out how fseek and ftell are working) I would suggest the following:
struct _stat buffer;
if (_stat("test.txt", &buffer) != 0) {
// stat failed, does file exist? Access?
}
else {
printf("Length of file %s is %i\n", "test.txt", buffer.st_size);
}
Note that I tested the syntax on Windows, and on Ubuntu, you might need to drop the underscore in front of stat.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
The error says no such file or directory i moved the file to the project folder
int main(int argc, const char * argv[]) {
int i;
char singleline[150];
FILE *file;
file = fopen("test.txt", "r");
puts(singleline);
if( file == NULL ) {
perror("Error: ");}
fclose (file);
}
return 0;
}
I guess you really need help debugging why this is happening to you.
Try adding some more code to your routine to help you determine what is going on. One thing to try is to call getcwd.
#include <unistd.h>
...
char buf[PATH_MAX];
printf("cwd: %s\n", getcwd(buf, sizeof(buf)));
...
This should report to you where your program thinks it is running from.
You report you get the following output:
cwd: /Users/ahmedhossam/Library/Developer/Xcode/DerivedData/assembler-doinswpyuiekhhemczblkainroaw/Build/Products/Debug `ֿ_\377
Start with that first, and I am guessing the next steps will become obvious to you.
The reported current working directory (hence, getcwd) is not your project folder. You can copy your file to that strange directory, or you can use chdir to change your working directory to be your project folder, or you can specify the absolute path to your file as suggested below.
You can avoid the problem altogether by specifying the absolute path to your file.
file = fopen("/the/absolute/path/to/test.txt", "r");
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I created a file called "text.txt" with a string inside and I want to copy that string in another file called "copiaqui.txt". But there's a problem. In the output file, I found this :
Why the program doesn't copy the string correctly?
Code :
#include <stdio.h>
#include <stdlib.h>
void copiaFile(FILE *fi, FILE *fo);
int main(void)
{
FILE *fi = fopen("test.txt", "r");
FILE *fo = fopen("copiaqui.txt","w");
if (fi == NULL)
{
printf("\nImpossibile aprire il file test.txt\n");
exit(EXIT_FAILURE);
}
if (fo == NULL)
{
printf("\nImpossibile aprire il file copiaqui.txt\n");
exit(EXIT_FAILURE);
}
copiaFile(fi, fo);
fclose(fi);
fclose(fo);
return 0;
}
void copiaFile(FILE *fi, FILE *fo)
{
int var;
while((var = getc(fi) != EOF))
{
printf("\nCarattere acquisisto : %c", var);
putc(var, fo);
}
}
You have made a common mistake with this expression:
var = getc(fi) != EOF
What this does is assign the value of (getc(fi) != EOF) to var, because of something called operator precedence. The value is either true or false. What you intended to do is:
(var = getc(fi)) != EOF
Which will make var have the getc() value, then check that against EOF.