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;
}
Related
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.
I am trying to read and write simple Infix and Postfix expressions to a from a file. When the program reaches the lines where fgets is called, an Access Violation error pops up.
Code:
#include <stdio.h>
#include <stdlib.h>
#include "header3.h"
char inFx[100], postFx[100];
int main() {
FILE *fp = fopen_s(&fp, "input.txt", "r");
remove("output.txt");
FILE *fp2 = fopen_s(&fp2, "output.txt", "a");
if (fp == 0)
{
printf("Could not open file\n");
}
else
{
int i = 0;
while (fgets(inFx, sizeof(inFx), fp)) { //access violation during runtime here
size_t ln = strlen(inFx);
int n = expEvaluate(inFx, ln, postFx); //refers to other class
if (inFx[ln] == '\n')
inFx[ln] = '\0';
if (fp2 == 0)
{
printf("Could not open file\n");
}
else
{
while (*(postFx + i) != 0)
{
fputc(*(postFx + i++), fp2);
}
fputc('\n', fp2);
}
}
}
fclose(fp2);
fclose(fp);
return 0;
}
fopen_s() returns an error code, NOT the file handle (that is assigned to the first parameter).
You should not get the result of fopen_s into your FILE pointers.
Also, you should put your test on fp2 before your loop. If you cannot open the File, then you will read your whole file fp but you won't do anything.
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));
I can see the last printf output of y but the fpc turns null.
I suspected for double quotes in fopen function but not could not find a solution: how to fix it?
Part of the code ;
char *y = &arr_lines[1024*2];
FILE *fpc = fopen(y, "r");
if (fpc == NULL) {
printf("Error opening file.\n");
//return -1;
}
printf("TEST %s\n",y);
When I run the code;
Error opening file.
TEST /Users/lessons/AbstractLesson.java
Here is the full code;
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#define LINESIZE 1024
int main(void){
char *arr_lines, *line;
char buf_line[LINESIZE];
int num_lines = 0;
char buf[10240];
// open file
FILE *fp = fopen("/tmp/file", "r");
//FILE *fp1 = fopen(arr_lines, "r");
if (fp == NULL) {
printf("Error opening file.\n");
return -1;
}
// get number of lines; from http://stackoverflow.com/a/3837983
while (fgets(buf_line, LINESIZE, fp))
if (!(strlen(buf_line) == LINESIZE-1 && buf_line[LINESIZE-2] != '\n'))
num_lines++;
// allocate memory
arr_lines = (char*)malloc(num_lines * 1024 * sizeof(char));
// read lines
rewind(fp);
num_lines = 0;
line=arr_lines;
while (fgets(line, LINESIZE, fp))
if (!(strlen(line) == LINESIZE-1 && line[LINESIZE-2] != '\n'))
line += LINESIZE;
// print first four lines
char *y = &arr_lines[1024*2];
FILE *fpc = fopen(y, "r");
//FILE *fp1 = fopen(arr_lines, "r");
if (fpc == NULL) {
printf("Error opening file.\n");
//return -1;
}
printf("TEST [%s]\n",y);
//x = &arr_lines[1024*0];
// y = *x;
// finish
fclose(fp);
return 0;
}
Change printf("TEST %s\n", y) to printf("TEST \"%s\"\n", y) so we can see if you have any extra whitespace characters in the filename.
fgets() returns the new line, if it's there. I didn't see where your code clears the newline. Does your path string include the new line?
Beyond that, fopen() is almost certainly working correctly. The only options are 1) The path is not correct, 2) the path has whitespace or other invalid characters, or 3) the file is not available for reading.
If you don't have a new line in your path, then you simply haven't provided enough information to resolve this issue.
I suspect the path, /Users/lessons/AbstractLesson.java, is wrong. It looks like an OSX path and it might be missing the username between Users and lessons.
I have this problem after I add some socket connection codes after following codes. What could be a reason when fp is ok, pointing some memory address, while reading the data (line 4), but when debugger(gdb) reaches the if block, fp pointer is just pointing 0x0.
#define CHANNELS_PER_IOM 25
...
int OldValues[CHANNELS_PER_IOM];
FILE * fp;
FILE * fp_t;
int buff;
int i;
fp = fopen("/windcom/tmp/dout_values", "r");
fp_t = fopen("/windcom/tmp/dout_values.tmp", "w");
i = 0;
while(fp && fscanf(fp, "%d\n", &buff) == 1) // fp is pointing some address here.
{
i++;
OldValues[i-1] = buff;
//printf("%d %d \n", OldValues[i-1], buff);
}
if(!fp) //fp is pointing 0x0 here.
{
for(i=0; i<CHANNELS_PER_IOM; i++)
{
OldValues[i] = 0;
}
}
Where is OldValues defined? You have probably not large enough and unfortunately the fp is getting overwritten inadvertently.
EDIT
Try this code:
while(i < CHANNELS_PER_IOM &&
fp &&
fscanf(fp, "%d\n", &OldValues[i++]) == 1) // fp is pointing some address here.
{
// Empty
}
EDIT 2
Put
And after
fp = fopen("/windcom/tmp/dout_values", "r");
put
if (!fp) printf("Unable to open file\n");
and this will check if the file is actually opened.