Keep counter in txt file - c

I am trying to keep a conter in txt file, I write a function and when I call the fuction, function should read the txt after, it should increment and write file.
In my txt ("test.txt") there is only one character. It is "0".
Code is here:
void readAndwrite(){
int total = 23;
FILE *fread, *fwrite;
fread = fopen("test.txt", "r");
fwrite = fopen("test.txt","w");
fscanf(fread,"%d",&total);
fclose(fread);
++total;
fprintf(fwrite ,"%d",total);
fclose(fwrite);
}
int main(int argc, char const *argv[])
{
readAndwrite();
readAndwrite();
readAndwrite();
readAndwrite();
readAndwrite();
readAndwrite();
return 0;
}
Why this is not working?

You can open twice but not in same time because the "w" flag destroy contents, so:
void readAndwrite(){
int total = 23;
FILE *f;
f = fopen("test.txt", "r");
if(!f) {
perror("File opening failed");
}
else{
fscanf(f,"%d",&total);
fclose(f);
printf("%d\n", total);
++total;
f = fopen("test.txt","w");
fprintf(f ,"%d",total);
fclose(f);
}
}
If you want to read/write in same time take a look to the doc and "w+" flag

Related

Invalid File Content When trying to read file in C

I am trying to read a file in C. First I am calculating the lines in the file:
int main(int argc, char* argv[])
{
if (argc < 2)
{
printf("No file specified");
exit(1);
}
FILE* pFile;
char currentCharacter;
int lines = 1;
pFile = fopen(argv[1], "r");
for (currentCharacter = getc(pFile); currentCharacter != EOF; currentCharacter = getc(pFile))
{
if (currentCharacter == '\n') lines++;
}
...
}
After calculating the lines in the file, I tried reading one by one, like this:
char currentLine[255];
for (int i = 1; i <= lines; i++)
{
fgets(currentLine, 255, pFile);
printf("%s\n", currentLine);
}
fclose(pFile);
But everytime I run it, I am getting this output:
²a
When I try to remove the for loop and place fgets() and printf() outside, it prints NOTHING
If you are wondering, here is the content of the file I am trying to read:
test.txt
test1
test2
test3
NOTE: The file is being successfully opened as it is counting the lines correctly.
As said in the comments, no need to count the lines. Just stop when there is nothing more to read. That is, when fgets returns NULL.
#include<stdio.h>
#include<stdlib.h>
int main(int argc, char* argv[])
{
if (argc < 2)
{
printf("No file specified");
exit(1);
}
FILE* pFile = fopen(argv[1], "r");
if(pFile==NULL)
{
printf("File is not found");
exit(1);
}
char currentLine[256];
while(fgets(currentLine, 256, pFile))
{
printf("%s", currentLine);
}
return 0;
}

How can I write or append the content fo text file then display?

How can I write and create the file, append if the file exists, then display all string file text? I can't append the content to at the end of file text, then display all strings. Thank for reading!
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
#include<unistd.h>
int main(int argc, char** argv) {
char c, filename[100], content[100];
FILE *fptr;
printf("File name: ");
scanf("%s", filename);
printf("Enter content: ");
gets(content);
if ((fptr = fopen(filename, "r")) == NULL)
{
fptr = fopen(fptr, "w");
fprintf(fptr,"%s", content);
}
else{
fptr = fopen(fptr, "a");
fprintf(fptr,"%s", content);
}
c = fgetc(fptr);
while (c != EOF)
{
printf ("%c", c);
c = fgetc(fptr);
}
fclose(fptr);
return 0;
}
If you want to open a file for reading and to also append to it, you can do that with just one call to fopen by using the mode a+.
fptr = fopen(filename, "a+");
if (fptr == NULL)
{
// Handle not being able to open the file
}
If the file doesn't exist, it will create it. The position for reading will be at the beginning of the file, but anything you write to it will be at the end.
There are lot of bugs as mentioned by others in comments. I tried to explain in comments, read it carefully.
int main(int argc, char** argv) {
char filename[100], content[100];
FILE *fptr;
printf("Enter content: \n");
fgets(content,sizeof(content),stdin); /*use fgets() instead of gets()*/
printf("File name: ");
scanf("%s", filename);
if ((fptr = fopen(filename, "r")) == NULL) {/*if doesn't exist */
fptr = fopen(filename, "w"); /*create it */
fprintf(fptr,"%s", content); /* and write it */
}
else{
/* it should be a+ if you want to read, as you are doing using fgetc() */
fptr = fopen(filename, "a+");/*if exist, write at end of file */
fprintf(fptr,"%s", content);/* write at end */
}
rewind(fptr);/* move the fptr to beginning to read further */
int c = 0; /* fgetc() returns integer */
while( (c = fgetc(fptr))!= EOF) {
printf ("%c\n", c);
}
fclose(fptr);
return 0;
}
Use fgets() instead of gets(). Read here Why is the gets function so dangerous that it should not be used?

Putting txt File Into Array is Starting at 12th Element

I'm writing a program in C, in which I am reading the data from a .txt file, and my goal is to put each element from the .txt file into an array. When I compile and run the program, the values of 50, 55, and 0 are returned. These are the ASCII values (I'm not sure why the elements are being stored as ASCII codes, but that's okay for now) for 2, 7, and 0 (meaning nothing was initialized since we reached the end of the .txt file. Why is my program not reading the .txt file from the beginning??
...
int main(int argc, char *argv[]){
FILE *inputFile;
char *input = argv[1];
char magicSquareArray[257];
inputFile = fopen(input, "r");
if (inputFile == 0){
printf("Cannot open file for reading!\n");
return -1;
}
fscanf(inputFile, "%s", magicSquareArray);
while (!feof(inputFile)){
fscanf(inputFile, "%s", magicSquareArray);
}
printf("%i\n", magicSquareArray[0]);
int sideSize = magicSquareArray[0];
int squareSize = sideSize * sideSize;
printf("%i\n", squareSize);
fclose(inputFile);
The text file:
3
4,3,8
9,5,1
2,7,6
Perhaps you want the code such as the following.
(However, I think in the following manner.
To prepare an array read the first number,
To assign a numerical value to read into it.)
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]){
FILE *inputFile;
char *input = argv[1];
char magicSquareArray[257];
int ch, len;
inputFile = fopen(input, "r");
if (inputFile == 0){
printf("Cannot open file for reading!\n");
return -1;
}
len = 0;
while((ch = fgetc(inputFile)) != EOF && len < sizeof(magicSquareArray)-1){
magicSquareArray[len++] = ch;
}
magicSquareArray[len] = 0;
fclose(inputFile);
printf("%c\n", magicSquareArray[0]);
int sideSize = atoi(magicSquareArray);
int squareSize = sideSize * sideSize;
printf("%i\n", squareSize);
return 0;
}

readFile function without fclose

I have a function to add new words to a .txt file. I still have to make a function to learn the vocabulary. Several times I have to read the file, so I try to make a function for it.
void readFile(FILE* fp, char *name){
if((fp=fopen(name,"a"))==NULL) {
printf("I cannot open file!\n");
exit(1);
}
}
And I don't want to close the file in this function, because in other functions I would operate on this file.
int main(){
FILE *file;
readFile(file,"verbs.txt");
fclose(file);
return 0;
}
If I try to close file like that, I get core dump. But if fclose is in a readFile it works well. So it is possible to write readFile function without fclose()?
Change it to:
void readFile(FILE** fp, char *name){
if((*fp=fopen(name,"a"))==NULL) {
printf("I cannot open file!\n");
exit(1);
}
}
int main(){
FILE *file=NULL;
readFile(&file,"verbs.txt");
//Use the file here after checking for NULL.
if (file != NULL)
fclose(file); //check for NULL before closing.
return 0;
}
All parameters in C are pass by value. Changing the value of fp in your function does not change the value in the calling function.
You can return the value and use that instead:
FILE *readFile(char *name){
FILE *fp;
if((fp=fopen(name,"a"))==NULL) {
printf("I cannot open file!\n");
exit(1);
}
return fp;
}
int main(){
FILE *file = readFile("verbs.txt");
fclose(file);
return 0;
}
If you want the readFile function to manage its own file pointer, I would do it more like this:
static FILE *fp = NULL;
void readFile(char *name){
if((fp=fopen(name,"a"))==NULL) {
printf("I cannot open file!\n");
exit(1);
}
}
void closeFile(){
if(fp!=NULL) {
fclose(fp);
fp = NULL;
}
}

C Programming - Read specific line from text file

Here is the code:
int main()
{
struct vinnaren
{
char vinnare[20];
int artal;
};
struct vinnaren v[10];
int inputrader;
int antalrader; //I want antalrader to be equal to the first
//line in test.txt(the first line is "5")
char file_name[256] = "test.txt";
char buf[512];
FILE *f = fopen(file_name, "r");
if (!f)
{
exit(0);
}
while (fgets(buf, sizeof buf, f))
{
printf("%s", buf);
}
fclose(f);
}
This is the code I have. I want to make it so that
antalrader = line1 in the file test.txt
How do I read a specific line from the file?
With this code you can read a file line by line and hence read a specific line from the text file:
lineNumber = x;
static const char filename[] = "file.txt";
FILE *file = fopen(filename, "r");
int count = 0;
if ( file != NULL )
{
char line[256]; /* or other suitable maximum line size */
while (fgets(line, sizeof line, file) != NULL) /* read a line */
{
if (count == lineNumber)
{
//use line or in a function return it
//in case of a return first close the file with "fclose(file);"
}
else
{
count++;
}
}
fclose(file);
}
else
{
//file doesn't exist
}
I got a really simple answer but I don't know if it is helping anyone:
int OpenCommand(int idOfCommand)
{
fscanf(file_ptr, "%[^idOfCommand]",a[idOfCommand]);
printf("%d\n", a[idOfCommand]);
system("pause");
return 0;
}

Resources