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 1 year ago.
Improve this question
struct Seats seats[12];
FILE* inp;
FILE* opt;
int counter = 1;
char option;
if ((inp = fopen("seats.bin", "rb")) == NULL) {// open file to read
printf("file did not open!");
exit(0);
}
fread(&seats, sizeof(struct Seats), 12, inp);// save file data to struct array
//later in the code
opt = fopen("seats.bin", "w");
fwrite(seats, sizeof(struct Seats), 12, opt);
fclose(inp);
i have no problems reading the data from the bin file. however when i try to write to the file it stores random values making it imposable to read when i boot up the program again.
if you guys know the problem i would appreciate the help
If you're on windows, it's important to write wb instead of only w on this line opt = fopen("seats.bin", "wb"); to refer to a binary file:
struct Seats seats[12];
FILE* inp;
FILE* opt;
int counter = 1;
char option;
if ((inp = fopen("seats.bin", "rb")) == NULL) {// open file to read
printf("file did not open!");
exit(0);
}
fread(&seats, sizeof(struct Seats), 12, inp);// save file data to struct array
//later in the code
opt = fopen("seats.bin", "wb");//w for write, b for binary
fwrite(seats, sizeof(struct Seats), 12, opt);
fclose(inp);
You need to check how many you actually read and only write that many. Otherwise if you read fewer than you expect you'll write out whatever garbage was in seats.
size_t num_read = fread(seats, sizeof(struct Seats), 12, inp);
// later
fwrite(seats, sizeof(struct Seats), num_read, opt);
Also...
Check fopen worked.
Use wb for writing binary, like rb. It's only important on Windows machines.
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 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 8 years ago.
Improve this question
Consider the following example code:
/* verify.c */
#include <stdio.h>
int
main (int argc, char *argv[])
{
if (argc < 2)
return 0;
char *filename = argv[1];
FILE *f = fopen(filename, "w");
if (!f)
perror("something went wrong");
// random data
#define SIZE 65536
#define ITER 1024
unsigned int buffer[SIZE] = { 0 };
unsigned int i;
for (i = 0; i < ITER; ++i)
{
int res = fwrite(buffer, sizeof(*buffer), SIZE, f);
if (res != SIZE)
perror("something went wrong");
}
fclose(f);
return 0;
}
Uninterestingly, his program will write random data to a file.
Interestingly though, the program is orders of magnitude faster, if the file does not exist, although its contents are not at all relevant to the program.
time ./verify notexists
real 0m0.162s
user 0m0.000s
sys 0m0.162s
time ./verify exists
real 0m3.807s
user 0m0.002s
sys 0m0.268s
Why is that?
EDIT:
thanks to #rodrigo's suggestion below, I ran both cases throuh strace, and it reported that the close system call takes a long time to complete if the file exists.
if the file exists:
close(3) = 0 <2.673454>
otherwise:
close(3) = 0 <0.000011>
When the file does exist, "w" will truncate it, that is, remove all its contents. That takes time, possibly a lot of time is the file is very big and the file system is not very good (FAT?).
Opposed to that, when the file does not exist, it will be created, that is to add a directory entry and an inode or whatever the file system uses. But these structures are always small, so it is not a big deal.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I want to open file in 20 loop. Every time the name of the folder changes.Like This variables1,variables2,variables3......variables20 I found the same question in here , but it didnt help me.
Here's what I have tried:
int l=1;
while(l<20){
char filename[10];
sprintf (filename, "variables%d", l);
OR
scanf("%s", filename);
FILE * fp;
if ((fp = fopen (filename,"rb")) == NULL){
printf("Failed to Open File variables%d\n",l);}
........... Reading Data........
fclose (fp);
l++;
}
I can wite Filename succesfully but I got the error: Failed to Open File variables1
[SOLVED] I am just sodding idiot.Thank you for your concern and answers... i just forgot to add ".bin" sprintf (filename, "variables%d.bin", l);
You never increment your counter.
I would also recommend you to use a for loop like this
for(int i = 1; i < 20; i++){
// Your code
}
Your filename buffer is too short - "variables1" requires 10 characters plus a '\0' terminator, so you need at least 11 characters for this buffer, and more when the index is > 9, otherwise you will get a buffer overflow and undefined behaviour. Change:
char filename[10];
to:
char filename[PATH_MAX]; // PATH_MAX is defined in <limits.h>
Also: if, as your title suggests, you want to write to these files, then you need to change:
if ((fp = fopen (filename,"rb")) == NULL){
to:
if ((fp = fopen (filename,"wb")) == NULL){