I am using Dev-C++ IDE, and now I am trying to do the file handling.here is my code :
int main(){
FILE *fp;
int b = 10;
int f;
fp = fopen("data.txt", "w");
//checking if the file exist
if(fp == NULL){
printf("File does not exist,please check!\n");
}else{
printf("we are connected to the file!\n");
}
fprintf (fp, " %d ", b) ;
fclose(fp);
printf("Reading from the file \n");
FILE *fr;
fr=fopen("data.txt","r");
fscanf (fr, " %d ", &f) ;
fclose(fr);
printf("the data from the file %d \n", f);
return 0;
}
this code is working in NetBeans, but in Dev-C++, I am just getting the message of "we are connected to the file", but it is not putting the value of "10" into the file. please you know the answer let me know, what should I do?
I can't see anything wrong with your code, but here are some tips
A good habit is to create functions and call these instead of having all inline e.g.
#define FILENAME "data.txt"
void writeFile()
{
FILE *fp;
int b = 10;
fp = fopen(FILENAME, "w");
//checking if the file exist
if (fp == NULL)
{
perror("File could not be opened for writing\n");
}
else
{
printf("File created\n");
}
fprintf (fp, " %d ", b) ;
fclose(fp);
}
void readFile()
{
int f;
printf("Reading from the file \n");
FILE *fr;
fr=fopen(FILENAME,"r");
fscanf (fr, " %d ", &f) ;
fclose(fr);
printf("the data from the file %d \n", f);
}
int main()
{
writeFile();
readFile();
}
then when reading from the file I would suggest you use fgets instead
as it is safer to use since fscanf has a tendency to cause memory overwrites
if values are unexpected.
<- fscanf(fp," %d ", &f );
-> char buf[16]; // some buffer
-> fgets( fp, buf, 10 ); // read as string
-> f = atoi(buf); // convert to int
it works perfectly. No issue with code of IDE. please shift the code in to "My documents" in windows. Try it.... I think its permission issue.
Related
I've used a ".txt" extension while reading and writing the file, also the file mode is corresponding to that of "text" type of file. The program runs fine, but instead of storing an ASCII character in the file, it is storing binary characters. I need some assistance here. Thank you.
int main(void)
{
FILE *fp;
int n2, n1;
printf("ENTER A NUMBER: ");
scanf("%d", &n1);
fp = fopen("hello.txt", "w");
if (fp == NULL)
{
printf("ERROR");
exit(1);
}
fprintf(fp, "%d", n1);
//fclose(fp);
//rewind(fp);
fp = fopen("hello.txt", "r");
if (fp == NULL)
{
printf("ERROR");
exit(1);
}
//n2 = getw(fp);
fscanf(fp, "%d", n1);
printf("%d", n1);
fclose(fp);
}
If you are going to close and reopen the file you don't need rewind. Or you can open the file to read and write, and then you can use rewind. Both work, here is a sample of the latter:
int main(void)
{
FILE *fp;
int n2, n1;
printf("ENTER A NUMBER: ");
if (scanf("%d", &n1) == 1) // checking if the input was correctly parsed
{
fp = fopen("hello.txt", "w+"); // open to read and write
if (fp == NULL)
{
printf("ERROR");
exit(1);
}
putw(n1, fp); // write to the file
rewind(fp); // go back to the beginning of the file
n2 = getw(fp); // get the data
printf("%d", n2);
fclose(fp);
}
else
{
puts("Bad input");
}
}
Live sample
There is still the matter of possible integer overflow when reading from stdin, if there is no requirement to guard against that, make sure to at least document the vulnerability, otherwise the advice is to use fgets to read input and strtol to convert the value.
You should send address of a variable in fscanf, like this:
fscanf(fp,"%d",&n1);
#include <stdio.h>
int main(void) {
int name;
int arrival_time;
int size;
int ret;
FILE * fp = fopen_s("C:\\NIA\\data.txt", "rt");
while (1)
{
ret = fscanf_s(fp, "%d %d %d", &name, &arrival_time, &size);
if (ret == EOF)
break;
printf("%d %d %d \n", name, arrival_time, size);
}
return 0;
}
I want to dump my txt file to project but errors are coming out. I'm confused about memory initiation and file format, variables, etc. How can I fix this and print values well?
My txt file is :
Your question lacks the most important information: What is going wrong.
When I compile your code, I get errors for fopen_s. (OK, this is mainly because I use gcc ;) )
The manual tells us how this function looks like:
errno_t fopen_s(
FILE** pFile,
const char *filename,
const char *mode
);
This means, you must use it like this:
errno_t err;
FILE *fp;
err = fopen_s(&fp, "C:\\NIA\\data.txt", "rt");
if (err != 0)
{
fprintf(stderr, "The file was not opened\n" );
exit(1);
}
Or you stick to standard functions and use them as you already tried:
FILE *fp;
fp = fopen("C:\\NIA\\data.txt", "rt");
if (fp = NULL)
{
fprintf(stderr, "The file was not opened\n" );
exit(1);
}
You should definitely add checks for all return values. At least for I/O related functions like fopen and scanf.
Also closing your file would be adviseable. While it is only opened in read mode, it will not cause much trouble as it is closed automatically on program termination, but it is surely good style to do it.
An improved version could look like this:
(As you do not scan strings, there is no benefit using MS non-standard function scanf_s)
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int name;
int arrival_time;
int size;
FILE * fp = fopen("data.txt", "rt");
if (fp == NULL) {
perror("File data.txt cannot be opened");
exit(1);
}
while (fscanf(fp, "%d %d %d", &name, &arrival_time, &size) == 3)
{
printf("%d %d %d\n", name, arrival_time, size);
}
fclose(fp);
return 0;
}
This prints the content of your data.txt file on the console.
If dumping you txt file means closing the txt file after using it, you can use the following
fclose(fp);
before the return 0;
#include <stdio.h>
main() {
int n;
FILE *file;
printf("We are here to create a file!\n");
file = fopen("demo.txt", "w+");
if (file != NULL)
printf("Succesfully opened!");
printf("Enter number\n");
while (scanf("%d", &n)) {
fprintf(file, "%d", n);
}
fclose(file);
}
why fscanf() is not working here? Here scanf is working properly but fscanf() is not responding or working here. Can anyone explain what the problem is?
Your code has some problems:
the prototype for main without arguments is int main(void)
you do not exit the program if the file cannot be opened. You will have undefined behavior if fopen returns NULL because you later pass this null pointer to fprintf.
the loop iterates until scanf() returns 0. You should instead iterate while scanf() returns 1. scanf() will return EOF if it fails at end of file, causing an infinite loop.
you should probably output a separator after the number in fprintf() otherwise all numbers are going to be clumped together forming a long sequence of digits.
main() should return 0 or an error status
Here is a corrected version:
#include <stdio.h>
int main(void) {
int n;
FILE *file;
printf("We are here to create a file\n");
file = fopen("demo.txt", "w");
if (file != NULL) {
printf("Successfully opened\n");
} else {
printf("Cannot open demo.txt\n");
return 1;
}
printf("Enter numbers\n");
while (scanf("%d", &n) == 1) {
fprintf(file, "%d\n", n);
}
fclose(file);
return 0;
}
Regarding your question: why can't I use fscanf() instead of scanf()?
you can use fscanf() as long as you give it a stream pointer opened for reading: if you write while (fscanf(stdin, "%d", &n) == 1) the program will behave the same way.
if you want fscanf() to read from file, you need to perform a file positioning command between read and write operations, such as rewind() of fseek(). Yet fscanf() will fail if there is no number to read at the current position in the file and since you open file with "w+" mode, fopen() will be truncated it.
You could cause an infinite loop by writing a number to the file, rewinding it to the beginning and re-reading the same number, etc.
Here is some code for illustration:
#include <stdio.h>
int main(void) {
int n;
FILE *file;
printf("We are here to create a file\n");
file = fopen("demo.txt", "w+");
if (file != NULL) {
printf("Successfully opened\n");
} else {
printf("Cannot open demo.txt\n");
return 1;
}
printf("Enter a number: ");
if (scanf("%d", &n) == 1) {
fprintf(file, "%d\n", n);
rewind(file);
while (fscanf(file, "%d", &n) == 1) {
printf("read %d from the file\n", n);
if (n == 0)
break;
rewind(file);
fprintf(file, "%d\n", n >> 1);
rewind(file);
}
}
fclose(file);
return 0;
}
Interaction:
We are here to create a file
Successfully opened
Enter a number: 10
read 10 from the file
read 5 from the file
read 2 from the file
read 1 from the file
read 0 from the file
I am having problems with copying txt files. I need to info from one file to another.
My code looks like this,
_tprintf (TEXT("%s\n"), FindFileData.cFileName);
memset(fileName, 0x00, sizeof(fileName));
_stprintf(fileName, TEXT("%s\\%s"), path, FindFileData.cFileName); //iegust
FILE *fptr = fopen(fileName, "r");//atver
fscanf(fptr,"%[^\n]",c); //iegust datus no faila
printf("Data from file:\n%s",a);
strcpy(a, c); //nokope datus
buffer2 = strtok (c, ","); //norada partraukumu un tadas lietas
while (buffer2) {
buffer2 = strtok (NULL, ",");
if(i<1){ printf("%s\n", c);}
i++;
while (buffer2 && *buffer2 == '\040'){
buffer2++;
// TODO ieliec iekavinas
}
}
And after that I use basic fputs().
My problem is that this code ignores new lines. It prints out fine, each string in it's own line, but that does not happen in file. (\n).
Your problem is that you just need to copy information from one file to another. So, why you don't use a simple solution to do it than your. I have a snipet code can solve your problem easily as shown below.
If I am wrong about your question, please give me advices.
#include <stdio.h>
#include <stdlib.h> // For exit()
int main()
{
FILE *fptr1, *fptr2;
char filename[100], c;
printf("Enter the filename to open for reading \n");
scanf("%s", filename);
// Open one file for reading
fptr1 = fopen(filename, "r");
if (fptr1 == NULL)
{
printf("Cannot open file %s \n", filename);
exit(0);
}
printf("Enter the filename to open for writing \n");
scanf("%s", filename);
// Open another file for writing
fptr2 = fopen(filename, "w");
if (fptr2 == NULL)
{
printf("Cannot open file %s \n", filename);
exit(0);
}
// Read contents from file
c = fgetc(fptr1);
while (c != EOF)
{
fputc(c, fptr2);
c = fgetc(fptr1);
}
printf("\nContents copied to %s", filename);
fclose(fptr1);
fclose(fptr2);
return 0;
}
If I have a pair of long functions:
#include <stdio.h>
#include <stdlib.h>
void writeData()
{
FILE *fp; int someVar1 = 1; int someVar2 = 2; int someVar3 = 3;
fp = fopen("results.dat", "a"); // open file
if (fp == NULL) {
printf("I couldn't open results.dat for appending.\n");
exit(0);
}
fprintf(fp, "%d\n", someVar1); // write to file
fprintf(fp, "%d\n", someVar2); // write to file
fprintf(fp, "%d\n", someVar3); // write to file
fclose(fp); // and close
}
void readData()
{
FILE *fp; int someVar1, someVar2, someVar3;
fp = fopen("results.dat", "r"); // open file for reading
if (fp == NULL) {
printf("I couldn't open results.dat for reading.\n");
exit(0);
}
fscanf(fp, "%d\n", &someVar1); // read from file
fscanf(fp, "%d\n", &someVar2); // read from file
fscanf(fp, "%d\n", &someVar3); // read from file
fclose(fp); // and close
printf("someVar: %d %d %d\n", someVar1, someVar2, someVar3);
}
int main(void)
{
writeData();
readData();
return 0;
}
Is there a way I can (ab)use the preprocessor to avoid duplicating read and write code? In other words, is there a way to generate pairs of fprintf(fp, "%d\n", someVar) and fprintf(fp, "%d\n", someVar) in the write() and read() functions respectively?
EDIT: this could equally apply to allocating/deallocating a whole load of memory, e.g. http://pastebin.com/wdAnHfWx. Basically any task which has a lot of code repetition between two complementary, but simple functions.
There is a technique known as X Macros that may fit to your needs. You can check a basic information of how it works in wikipedia (http://en.wikipedia.org/wiki/X_Macro).
Following the wiki explanation, you could create a VAR_LIST, and later expand this list as read or write.
#define MY_VAR_LIST(ENTRY) \
ENTRY(var1) \
ENTRY(var2) \
ENTRY(var3)
#define EXPAND_AS_DEFINITION(my_var) int my_var;
#define EXPAND_AS_WRITE(my_var) fprintf(fp, "%d\n", (my_var));
#define EXPAND_AS_READ(my_var) fscanf(fp, "%d\n", &(my_var));
int my_function_write()
{
MY_VAR_LIST(EXPAND_AS_DEFINITION)
FILE *fp;
fp = fopen("results.dat", "a"); // open file
if (fp == NULL) {
printf("I couldn't open results.dat for appending.\n");
exit(0);
}
MY_VAR_LIST(EXPAND_AS_WRITE)
fclose(fp);
}
int my_function_read()
{
MY_VAR_LIST(EXPAND_AS_DEFINITION)
FILE *fp;
fp = fopen("results.dat", "r"); // open file
if (fp == NULL) {
printf("I couldn't open results.dat for appending.\n");
exit(0);
}
MY_VAR_LIST(EXPAND_AS_READ)
fclose(fp);
}
So to append a new var, you just need to update your VAR_LIST.
I did not tried to compile my code, so there is probably some syntax error, but that is the way it should work.
Why preprocessor? You can to that right in code, something like this
#define READ 0
#define WRITE 1
void do_some_io( int action )
{
FILE *fp; int someVar = 1;
fp = fopen("results.dat", (action == WRITE ? "a" : "r") ); // open file
if (fp == NULL) {
printf("I couldn't open results.dat for io.\n");
exit(0);
}
if ( action == WRITE )
fprintf(fp, "%d\n", someVar); // write to file
else
fscanf(fp, "%d\n", &someVar); // read from file
fclose(fp); // and close
}
Looking at your code, I'd say it's not worth the effort, because there are too many differences in it ("a" vs. "r" in open, different error messages, printf vs. scanf, extra printf). The whole thing will be messy to create and even more messy to undestand if someone will have to read or debug it a year later.
However, for educational purposes:
#define MYFUNC(NAME,VARPART1,VARPART2) \
void NAME () { \
int a= 0; \
VARPART1; \
VARPART2; \
}
// make a print function
MYFUNC(printit, printf("%d", a), return);
// make a scan function:
MYFUNC(scanit, scanf("%d", &a), *global= a);
will create two different functions with one macro, e.g the first will be:
void printit () {
int a= 0; \
printf("%d", a);
return;
}