C passing File stream as a function parameter - c

This function gives infinite loop. Any Help? And is it even possible to pass file stream to a function as argument.
#include<stdio.h>
#include<stdlib.h>
void fcopy(FILE *inFILE1){
FILE *inFILEcopy;
char a;
inFILEcopy=fopen("C:/Users/labuser.pcroot-PC.003/Desktop/empoleecopy.bak","w");
do{
a=fgetc(inFILE1);
fputc(a,inFILEcopy);
if(feof(inFILE1))break;
}while(1);
}
int main(){
FILE *inFILE;
inFILE=fopen("C:/Users/labuser.pcroot-PC.003/Desktop/empolee.dat","w");
fputs("My name is Anthony",inFILE);
fcopy(inFILE);
}

To summarize mine and Phil Brubaker comments, modify your code in this way:
#include<stdio.h>
#include<stdlib.h>
void fcopy(FILE *inFILE1) {
FILE *inFILEcopy;
char a;
inFILEcopy = fopen("C:/Users/scifani/Desktop/empoleecopy.bak", "w");
do{
a = fgetc(inFILE1);
fputc(a, inFILEcopy);
if (feof(inFILE1))break;
} while (1);
fclose(inFILEcopy);
}
int main(){
FILE *inFILE;
inFILE = fopen("C:/Users/scifani/Desktop/empolee.dat", "w");
fputs("My name is Anthony", inFILE);
fclose(inFILE);
inFILE = fopen("C:/Users/scifani/Desktop/empolee.dat", "r");
fcopy(inFILE);
}

FILE* fcopy(char* yourFile) { // Or parse a FILE like you did but with a pointer
FILE *inFILEcopy;
inFILEcopy = fopen("C:/Users/labuser.pcroot PC.003/Desktop/empoleecopy.bak", "w");
if (inFILEcopy == NULL)
return NULL; // You'll have to check null to see if fcopy() failed
FILE* inFILE1 = fopen(yourFile, "r");
if (inFILE1 == NULL) {
puts("File to be copied does not exist.\n");
return NULL;
}
for (char a = fgetc(inFILE1); feof(inFILE1);)
{
fputc(a, inFILEcopy);
if (ferror(inFILE1) || ferror(inFILEcopy)) { // If error in one of the two files
if (fclose(inFILE1))
puts("Couldn't close inFILE1\n");
if (fclose(inFILEcopy));
puts("Couldn't close inFILEcopy\n");
puts("Error during copy.\n");
return NULL;
}
}
return inFILEcopy;
}
int main() {
FILE *inFILE;
inFILE= fopen("C:/Users/labuser.pcroot-PC.003/Desktop/empolee.dat","w");
if (inFILE != NULL)
{
fputs("My name is Anthony", inFILE);
if (!ferror(inFILE) || fclose(inFILE)) // If no error when writing and closing works, we can copy
{
inFILE = fcopy("C:/Users/labuser.pcroot-PC.003/Desktop/empolee.dat");
if (inFILE != NULL)
puts("Copy success\n");
}
}
}
I think this is the best way to do this. I am open to any improvement though. Check this link if you have any question regarding the error checkings, someone explains the best way to do so. This should work perfectly.

Related

How to replace /home/ubuntu/... in cs50 IDE

I am trying to write a program in C within a file pointer, but the problem is I only managed to write the file path like this:
char *line = gtline("/home/ubuntu/games/cards-against-humanity/black-cards/single/1/file1.txt", 3);
but I would like to replace /home/ubuntu/games with something else so I can download the whole directory /cards-against-humanity and the program still points to the file /file1.txt.
I've tried with /~ and with /. but it gives me Segmentation fault I suppose when the program trys to open the file.
Thanks in advance.
Update: gtfile function is a function i created by myself here's the declaration:
char *gtline(char *s, int i)
{
FILE *file;
char *filename = s;
static char buffer[MAX_LINE];
int read_line = i;
file = fopen(filename, "r");
if (file == NULL)
{
printf("Error opening file.\n");
fclose(file);
return NULL;
}
bool keep_reading = true;
int current_line = 1;
do
{
fgets(buffer, MAX_LINE, file);
if (current_line == read_line)
{
keep_reading = false;
}
if (feof(file))
{
keep_reading = false;
}
else
{
buffer[strlen(buffer)-1] = '\0';
}
current_line++;
} while (keep_reading);
fclose(file);
return buffer;
}

Lines containing given word in output file C

I am very new to working with files and I can't seem to get my head around this. What I am trying to do is to write in the Exit.txt file all the lines that have my given word in them. For example, if my word is "exercise" and my In.txt contains the following:
I exercise daily
I like apples
How often do you exercise
I am tired
Then in Exit.txt I should have
I exercise daily
How often do you exercise
The problem is that somehow it only writes the last line in the Exit.txt file, and sometimes it doesn't even write anything, depending on my input In.txt.
I would very much appreciate any help, thank you very much!
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
FILE* fis, * fis2;
char* sir, * rez, word[50];
printf("Word: ");
gets(word);
sir = malloc(50 * sizeof(char));
fis = fopen("In.txt", "rt");
if (fis == NULL)
printf("Can't open file!");
else
{
while (!feof(fis))
{
rez = fgets(sir, 50, fis);
if (strcmp(rez,word)==0)
{
fis2 = fopen("Exit.txt", "wt");
fputs(sir, fis2);
}
}
}
fclose(fis);
free(sir);
return 0;
}
When you open a file for writing in a loop you must know about the offset. Its better open file in append mode, write your data and close it.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
FILE* fis, * fis2;
char* sir, * rez, word[50];
char *line = NULL;
ssize_t bufsiz = 0;
ssize_t nbytes;
printf("Word: ");
gets(word);
fis = fopen("In.txt", "rt");
if (fis == NULL)
printf("Can't open file!");
else
{
while ((nbytes = getline(&line, &bufsiz, fis)) != -1)
{
char * ptr_value = strstr(line,word);
if(ptr_value != NULL) {
printf(line);
fis2 = fopen("Exit.txt", "a");
fputs(line, fis2);
fclose(fis2);
}
}
}
fclose(fis);
return 0;
}
there are a few changes needed to get your code working:
only open the output file once (so not in the while loop)
to check if a string is a part of another string please use "strstr" and not "strcmp"
don't forget to close your file at the end
So here is a suggestion for a solution
int main()
{
FILE* fis, * fis2;
char* sir, * rez, word[50];
printf("Word: ");
gets(word);
sir = malloc(50 * sizeof(char));
fis = fopen("In.txt", "rt");
if (fis == NULL)
printf("Can't open file!");
if ((fis2 = fopen("Exit.txt","wt"))==NULL){
printf("Cant't open Exit-file\n");
return EXIT_FAILURE;
}
else
{
while (!feof(fis))
{
rez = fgets(sir, 50, fis);
if(strstr(rez,word)!=NULL)
{
fputs(sir, fis2);
}
}
}
fclose(fis);
fclose(fis2);
free(sir);
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;
}
}

Pass stream by reference

I am suppose to pass stream, which is a pointer, by reference. So I am passing this as a pointer to a pointer. Can someone please verify my code?
int main(int argc, char** argv)
{
FILE *stream;
printf("LINES: %d\n",scan(stream));
}
int scan(FILE *(*stream))
{
stream = fopen("names.txt", "r");
int ch = 0, lines=0;
while (!feof(*stream))
{
ch = fgetc(*stream);
if (ch == '\n')
{
lines++;
}
}
fclose(*stream);
return lines;
}
No output received.
Your code has design issues. What exactly do you want to achieve?
If you just want to count the lines, make the FILE * local to your function:
int count_lines(const char *filename)
{
FILE *stream = fopen(filename, "r");
int lines = 0;
while (1) {
int c = fgetc(stream);
if (c == EOF) break;
if (c == '\n') lines++;
}
fclose(stream);
return lines;
}
If you want to do a regular file operation (read, write, seek, rewind etc.) to a file that has already been opened with fopen, just pass the handle as FILE *:
int fget_non_space(FILE *stream)
{
int c;
do {
c = fgetc(stream);
} while (isspace(c));
return c;
}
In that case, both fopen and fclose are called outside this function. (You don't call fclose in your program, which you should, even if the operating system makes sure to close the file automatically after exiting.)
Passing a pointer to the file handle, FILE **, makes sense only if you want to change that file handle itself in the function, for example by calling fopen:
int fopen_to_read(FILE **FILE pstream, const char *fn)
{
*pstream = fopen(fn, "r");
return (*pstream != NULL) ? 0 : -1;
}
Even then, it would be better to return the file handle, as fopen does.
Your example code leaves the open filehandle accessible in main, but you don't do anything with it, you don't even close it. Is that what you want? I doubt it.
Use
int scan(FILE **stream) //no need for brackets
{
*stream = fopen("names.txt", "r"); //* is for dereferencing
if(*stream==NULL) // Checking the return value of fopen
{
printf("An error occured when opening 'names.txt'");
return -1;
}
int ch = 0, lines=0;
while ((ch = fgetc(*stream))!=EOF) //while(!feof) is wrong
{
if (ch == '\n')
{
lines++;
}
}
fclose(*stream); // Close the FILE stream after use
return lines;
}
int main(void)
{
FILE *stream;
printf("LINES: %d\n",scan(&stream)); //Pass address of `stream`. The address is of type `FILE**`
}
Replace
stream = fopen("names.txt", "r");
with
*stream = fopen("names.txt", "r");
Also
printf("LINES: %d\n",scan(stream));
with
printf("LINES: %d\n",scan(&stream));

Segfault - fclose / fopen

I'm having trouble with my following C code :
int main(void){
FILE* infile = fopen("file","r);
FILE* fp = NULL;
unsigned char* buffer = malloc(512);
while( fread(buffer,512,1,infile) > 0 ){ //reading a file block by block
if(buffer[0] == 0xff){
... //defining variable "name"
if(fp != NULL)fclose(fp);
fp = fopen(name,"w+");
fwrite(buffer,512,1,fp);
} else if(fp != NULL) {
fwrite(buffer,512,1,fp);
}
}
}
It seems that i can't fopen after fclose using the same pointer, why ? I need my pointer to remain accessible everywhere in the main so i can't declare a new one in my while.
EDIT: Oh god, problem solved. I was probably super tired. I was compiling the wrong file. Anyway...
Thanks, folks !
It's hard to tell why since you aren't showing us all of your code. However, reopening the file should be pretty straightforward:
#include <stdio.h>
int main(void)
{
FILE* fp = NULL;
char name[] = "somefile";
for (;;)
{
// do something
if ((fp = fopen(name, "w+")) == NULL)
break;
// do something with the file
fclose(fp);
// do something
}
return 0;
}

Resources