How to dynamically change filename while writing in a loop [closed] - c

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){

Related

Probelm with fscanf in C [closed]

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 1 year ago.
Improve this question
Ok, so i've been having a probelm with using int and char for my function. And is getting an error message enter image description here want to know how i should fix this with the code that i have:
#include<stdio.h>
#include<stdlib.h>
int main()
{
FILE *fp;
char name[100];
int roll_no, chars;
float marks;
fp = fopen("records.txt", "r");
if(fp == NULL)
{
printf("Error opening file\n");
exit(1);
}
printf("Testing fscanf() function: \n\n");
printf("Name:\t\tRoll\t\tMarks\n");
while( fscanf(fp, "Name: %s\t\tRoll no: %d\t\tMarks: %f\n"
, name, &roll_no, &marks) != EOF )
{
printf("%s\t\t%d\t\t%.2f\n", name, roll_no ,marks);
}
fclose(fp);
return 0;
}
The intedend output was this... enter image description here
Advice/help on how to use the char function at line 8 would be appericated
NOTE: This answer refers to revision 1 of the question. Meanwhile, OP has clarified the question and is asking for additional help concerning a related issue. That is why this answer does not fully address the question in its current state.
That's not an error message, that is simply a warning because you declare the variable 'chars' on line 8 and never use it in your program. Your program should be able to run even if there are compiler warnings, which are different from compiler errors.

Writing to a file. Creates file but does not write in it [closed]

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;
}

Can't read file in C [closed]

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.

How to open file in C, what is different between (argv[1], "r") and ("file name", "r") [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
How to open file by (argv[1], "r")?
My lab3.txt file is in same directory folder.
I can open file by
FILE *f = fopen("lab3.txt", "r");
but why I cannot open file by
FILE *f = fopen(argv[1], "r");
code:
int main(int argc, char **argv){
char buf[512];
FILE *f = fopen(argv[1], "r");
if (f == NULL)
{
printf("Error!\n");
}
fread(buf, 512, 1, f);
printf("buf: %s\n", buf);
if (chkserial(buf) == 0)
fullversion();
else
trialversion();
return 0;
}
You need to check the argument count your process that's running the program executable holds, and then make sure you are also calling it with the right amount of cli arguments.
Cli arguments are laid out as follows
<program> <foo.txt> <doo.txt> ...
argv[0] argv[1] argv[2] ... argv[n]
Therefore, you want to call your executable like this
your_exec_name lab3.txt
You may also want to add a check to make sure the program is run with at least one argument to prevent a segfault or passing in NULL to fopen
if(argc < 2) { /*Handling goes here*/ exit(1);}

Finding string in HTML file with C [closed]

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 have a HTML file that I've retrieved through curl and I wanted to find certain strings in the file so that I could analyse whether I have received the response I expected.
Here's the function I'm using to search for my string:
int find_str(FILE *infile, char *str)
{
char tmp[512];
while(fgets(tmp, sizeof(tmp), infile) != NULL)
{
if (strstr(tmp, str) != NULL)
{
printf("found %s in file\n", str);
return 1;
}
}
fprintf(stderr, "Couldn't Find %s in file!\n", str);
return 0;
}
and it's called as follows:
if(find_str(html_file, "<h1>Hello World</h1>") == 1)
{ ... }
First, the string is never found even when it is present. Second, this function is called in another if statement if the first should fail, but while watching execution in the debugger, it completely skips the while loop. No garbage values are given. If I watch the tmp array, the values seem normal, although they seem to have been encoded.
With that function, if your search string sits around 512 byte boundaries in the file, it won't match because you only check inside 512 byte blocks.
To fix this issue, you can load the whole file into memory instead. This also has an advantage on performance if you decide to search multiple times, as you won't have to do I/O every time.
This should work to read a file into memory:
fseek (infile, 0 , SEEK_END);
int filesize = ftell (infile);
rewind (infile);
char *whole_file = malloc(filesize+1);
if (!(filesize == fread(whole_file, filesize, 1, infile))) {
// ERROR
}
whole_file[filesize] = '\0';

Resources