Writing to a file within a folder in C - c

How can I do this?
I know opening a new file is something akin to this:
fpcon=fopen("konf_in","w");
printf("Whatever I want to input");
fclose(fpcon);
The output file only needs to be a simple .txt or .dat file

To write to a file, you need to call fprintf and pass your file pointer which is fpcon, see this example:
char name[20];
int number;
FILE *f;
f = fopen("/your_folder/sample.txt", "w");
if (f == NULL) {
printf("Error opening file!\n");
exit(1);
}
printf("\nNew contact name (max 19): ");
fgets(name, sizeof(name), stdin);
printf("New contact number: ");
scanf("%d", &number);
fprintf(f, "%s - %d\n", name, number);
fclose(f);
This page gives you further intel on how to handle file writes, appends, etc.
Just for clarification, the allowed modes for fopen are as follows:
r - open for reading
w - open for writing (file need not exist)
a - open for appending (file need not exist)
r+ - open for reading and writing, start at beginning
w+ - open for reading and writing (overwrite file)
a+ - open for reading and writing (append if file exists)

Related

Not able to open a file in read mode in c

char fileName[20];
puts("Enter the date.\n");
scanf("-> %s", fileName);
//Read the file
FILE *ptr;
ptr = fopen(fileName, "r");
if(ptr == NULL)
{
printf("\nNo file was found with this name\n");
exit(0);
}
else
{
printf("\nI FOUND the file.\n");
}
fclose(ptr);
I just want the user to enter a file name and then display 'found the file' as of now however even when the this code file and the text file are in same directory I am always getting the message'No file was found with this name' and I assure you that I am inputting the right file name(along with .txt extension).
Thank you #kaylum I got the answer.
The problem is with the scanf() statement. The scanf("-> %s", fileName) statement wants the user to input only -> otherwise it will fail.

C - fopen text file after building - OpenWRT - opkg

I have these lines in my C program:
int main(int argc, char **argv) {
int i=0, p=0;
FILE* fp;
fp = fopen("jacina.txt", "w+");
fscanf (fp, "%d", &i);
if (ftruncate(fp, 0) == -1) {
perror("Could not truncate")
};
p = i+10;
fprintf(fp, "%d", p);
}
After building this code to OPKG in OpenWRT (from Ubuntu), how can I read and write to this textual file which is located on any disk location where is located this OPKG?
Your code doesn't make any sense. To write the input given by user to a file:
Create a file first. Take input from user (say any string) and write it to the file with the help of file descriptor (fp) and close the file so that all buffers get flushed.
FILE *fp;
char comment[100] = {0};
fp=fopen("tempfile.txt","w");
if (fp == NULL)
{
printf("Error opening file!\n");
exit(1);
}
printf("Enter String: ");
gets(comment);
fwrite(comment, sizeof(comment), 1, fp) ;
fclose(fp);
fprintf() too can be used instead to write data into a file.
Similarly to read from a file you can use fgets() or fread() to store the contents of the file in a buffer and display the contents of the file. Hope it helps.

unable to read a file in c language. it creates a new file instead of reading it

I have creates a file in directory and want to read it in. I am using the following code to open and read a file in C-Language. But it creates a new file instead of reading the old file.
int main()
{
FILE * file;
file = fopen ("file", "r+");
//file reading code
fclose(file);
return(0);
}
you are using 'r+' mode to open the file. It creates a new file if not already exist in the directory. see the following code for your help.
int main()
{
FILE * file;
file = fopen ("file", "r");
if(file !== NULL)
// to do file reading code
else
printf("error in reading file");
fclose(file);
return(0);
}
also check the file name that you are using in fopen() function.It is case sensitive and also check the extension of that file e.g; .txt or .data or what ever. e.g;
file = fopen ("File.txt", "r");
If you only intend to read from a file then open it for reading, i.e. mode r (notice no +):
file = fopen ("file", "r");
I agree with answers given but you can also additionally check if file is present or not. Something as below. In case program does not recognize the file it will let you know. Avoid using r+ in case you want to read an already existing file.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char ch, file_name[25];
FILE *fp;
printf("Enter the name of file you wish to see\n");
gets(file_name);
fp = fopen(file_name,"r"); // read mode
if( fp == NULL )
{
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);
fclose(fp);
return 0;
}

Storage manager function to read block of a file

I am implementing a storage manager to open, create, read and write a file using file pointers and file handler. But i am not able to write efficient code to implement all of my read functions of my storage manager. The read function of my storage manager has to implement the following:
To read first block of a file
To read current block of a file
To read previous block of a file
To read next block of a file
To read last block of a file
Any suggestions and code examples would be helpful to me.
The following is the code written by me to read a data file using file pointer -
*/
#include
#include
void main()
{
FILE *fptr;
char filename[15];
char ch;
printf("Enter the filename to be opened \n");
scanf("%s", filename);
/* open the file for reading */
fptr = fopen(filename, "r");
if (fptr == NULL)
{
printf("Cannot open file \n");
exit(0);
}
ch = fgetc(fptr);
while (ch != EOF)
{
printf ("%c", ch);
ch = fgetc(fptr);
}
fclose(fptr);
}

How do I read and edit a .txt file in C?

I'm writing a program for an ATM. My .txt file is an account balance amount (in this case, 1500.00). How do I read in the .txt file, edit the account balance, and then save it to the file?
For example, if I were to ask a user to enter a deposit an amount of 300.00, I want to be able to add that 300.00 to the existing 1500.00 in the file, and then overwrite the 1500.00 with the total amount of 1800.00.
This is what I have so far.
float deposit;
float var;
printf("Current account balance:");
if ( (file_account = fopen ("account.txt", "r")) == NULL)
{
printf ("Error finding account balance.\n");
return;
}
while ( (fscanf (file_account, "%c", &var)) != EOF)
{
printf ("%c", var);
}
printf ("\n");
fclose (file_account);
for (deposit=0; deposit>0; deposit++)
{
if (deposit > 0)
{
printf ("Enter amount to deposit:");
scanf ("%f", &deposit);
//file_account + deposit;
fprintf (file_account, "Your new account balance is: %f", deposit);
}
else
{
printf ("Amount must be 0 or more.");
}
fclose (file_account);
}
You should use a File pointer to open & read the file, modify the contents according to your will and write back to file.
For example:
File *fp; // creates a pointer to a file
fp = fopen(filename,"r+"); //opens file with read-write permissions
if(fp!=NULL) {
fscanf(fp,"%d",&var); //read contents of file
}
fprintf(fp,"%d",var); //write contents to file
fclose(fp); //close the file after you are done
You need a few steps here:
int triedCreating = 0;
OPEN:
FILE *filePtr = fopen("test.txt", "r+");
if (!filePtr)
{
// try to create the file
if (!triedCreating)
{
triedCreating = 1;
fclose(fopen("test.txt", "w"));
goto OPEN;
}
fprintf(stderr, "Error opening file %i. Message: %s", errno, strerror(errno));
exit(EXIT_FAILURE);
}
// scan for the float
float value = 0.0f;
fscanf(filePtr, "%f", &value);
printf("current value: %f\nvalue to add: ", value);
// add the new value
float add = 0.0f;
scanf("%f", &add);
value += add;
// write the new value
fseek(filePtr, 0, SEEK_SET);
fprintf(filePtr, "%f", value);
fclose(filePtr);
You may wish to have different formatting for your printf()'s so that it looks nicer when read into a normal text editor.
you can read and edit a file with the help of basic FILE I/O(Input/ output) function in C i an simple manner like for example,writing to a file if it exist and if doesn't create a file with a name and then write to it.
A basic tutorial can be found at
http://www.tutorialspoint.com/cprogramming/c_file_io.htm
Now if you are talking about the complex .txt file having a lot of content in it and then you need to find a particular word and change it, i find it a bit difficult rather possible in Linux where you can call a script to read a file , edit it using SED,( stream editor for filtering and transforming text).You can find tutorials for it at below links
http://www.panix.com/~elflord/unix/sed.html

Resources