File reading in C starts from the middle of the file - c

I'm trying to read in a file and printing it all out but for some reason it starts doing so from almost the middle of the file, I've tried a few different methods of reading but none of them work as expected. This is the code. Thank you in advance.
void readFile(FILE *file) {
FILE * fd = fopen((const char *) file, "r");
if (fd == NULL) {
printf("Error");
}
char line[500];
while (!feof(fd)) {
fgets(line, 500, fd);
printf("%s",line);
}
fclose(fd);
}
int main() {
readFile((FILE *) "ulysses.txt");
return 0;
}

Related

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

C passing File stream as a function parameter

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.

Read the next line of a file every time a function is called

I have a text file with numbers on each line. I want to write a function in C that reads in the file and returns the next number in the file every time the function is called.
For example if I have these numbers:
100
200
300
400
and a function called get_number(), if I call get_number() it will return 100, if I call it again, it will return 200, etc.
This is what I've written so far but every time the function is called, it always goes back to the first number in the text file.
int * get_number()
{
FILE* file = fopen("random_numbers.txt", "r");
char line[256];
if (file==NULL)
{
perror ("Error reading file");
}
else
{
fgets(line, sizeof(line), file);
printf("%s", line);
}
return 0;
}
here's a version that does exactly that :
int * get_number(long* pos)
{
FILE* file = fopen("random_numbers.txt", "r");
char line[256];
if (file==NULL)
{
perror ("Error reading file");
}
else
{
fseek(file , *pos , SEEK_CUR);
fgets(line, sizeof(line), file);
printf("%s", line);
}
*pos = ftell(file);
return 0;
}
and you call it from main like this
long pos = 0;
get_number(&pos);
or better yet use a static variable
int * get_number()
{
static long pos = 0;
FILE* file = fopen("random_numbers.txt", "r");
char line[256];
if (file==NULL)
{
perror ("Error reading file");
}
else
{
fseek(file , pos , SEEK_CUR);
fgets(line, sizeof(line), file);
printf("%s", line);
}
pos = ftell(file);
return 0;
}
It's a good idea to avoid opening a file repeatedly. Instead of opening the file every time you call the function, open it once, then pass a file pointer to the function each time you call it.
int * get_number(FILE *file)
{
char line[256];
fgets(line, sizeof(line), file);
printf("%s", line);
return 0;
}
int main()
{
FILE *file = fopen("random_numbers.txt", "r");
if (file == NULL)
{
perror("Error opening file");
return 1;
}
while (!feof(file))
{
get_number(file);
}
fclose(file);
}
Open the file in the calling function.
Pass the FILE* to get_number.
Return an int from get_number, not an int*.
Here's a modified get_number.
int get_number(FILE* file)
{
// This is the core functionality.
// You should add error handling code
int number;
int n = fscanf(file, "%d", &number);
if ( n != 1 )
{
// Add error handling code.
}
return number;
}
This is normal, because you open your file each time you call get_number(); (this is even worse because no fclose are called.
What you want maybe is giving a file descriptor at get_number(); in this way :
void get_number(FILE* file)
{
char line[256];
if (file==NULL)
perror ("Bad descriptor given");
else
{
if (fgets(line, sizeof(line), file) == NULL)
perror("Fgets failed");
else
printf("%s", line);
}
}
And what you want, outside your function, is to do the following :
FILE * file = fopen("random_numbers.txt", "r");
get_number(file); // 100
get_number(file); // 200
fclose(file);
I made your function void, because the return here is pointless. You could change that and use atoi and the return fonction.

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

Copying Binary Files

I'm trying to figure out how to copy binary files from one place to another .exe's. I can't seem to find any solutions to learn.
I'm using Windows. What's the best way to do it?
What do you mean "best way"? I think this is the most straightforward way ... hopefully that is what you meant :)
fopen the input and output files with binary mode
FILE *exein, *exeout;
exein = fopen("filein.exe", "rb");
if (exein == NULL) {
/* handle error */
perror("file open for reading");
exit(EXIT_FAILURE);
}
exeout = fopen("fileout.exe", "wb");
if (exeout == NULL) {
/* handle error */
perror("file open for writing");
exit(EXIT_FAILURE);
}
fread and fwrite
size_t n, m;
unsigned char buff[8192];
do {
n = fread(buff, 1, sizeof buff, exein);
if (n) m = fwrite(buff, 1, n, exeout);
else m = 0;
} while ((n > 0) && (n == m));
if (m) perror("copy");
and finally close the files
if (fclose(exeout)) perror("close output file");
if (fclose(exein)) perror("close input file");
Have fun!
Windows has a CopyFile API (if you don't mind being platform specific). One thing to be careful of these days is making sure you have permissions to write to the destination area.
Make sure you open the files with the O_BINARY option if you use open() and file descriptors, or with the letter "b" in the mode string if you use fopen(). Note that O_BINARY is not standard except on Windows; however, you can treat it (or define it) as 0 on Unix and all will be fine. If you are using a pure Windows API, then make sure you are doing the equivalent - make sure you specify that the file is treated as a binary file.
You can use this to copy Binary Files:
int get_file_size(char *source)
{
FILE *fichier = fopen(source,"rb");
fseek(fichier,0,SEEK_END);
int size = ftell(fichier);
fseek(fichier,0,SEEK_SET);
fclose(fichier);
return size;
}
void copy(char *source, char *dest)
{
int srcsize = get_file_size(source);
char *data = (char *)malloc(srcsize);
int fsource = open(source,O_RDONLY | O_BINARY);
int fdest = open(dest,O_WRONLY | O_CREAT | O_BINARY);
read(fsource,data,srcsize);
write(fdest,data,srcsize);
close(fsource);
close(fdest);
}
You can use function of 'dos.h' for low-level IO operation.
Following code illustrate use of them. Hope it will helpful
#include<stdio.h>
#include<dos.h>
#include<FCNTL.H>
#include<SYS\STAT.H>
void main()
{
char s_file[100],d_file[100],buf[512];
short char copy='y';
int in_handle,out_handle,flg,len;
printf("\nEnter File Name : ");
fflush(stdin);
gets(s_file);
printf("\nEnter Destination File Name : ");
fflush(stdin);
gets(d_file);
// open file for reading
in_handle=open(s_file,O_RDONLY | O_BINARY);
if(in_handle<0)
{
printf("\nSource File not Found... ");
}
else
{
// open file for writing
out_handle=open(d_file,O_CREAT|O_WRONLY|O_BINARY,S_IWRITE);
while((len=read(in_handle,buf,512))>0)
{
flg=write(out_handle,buf,len);
if(flg==-1)
break;
}
if(flg==-1)
{
printf("Unable to Create");
}
else
{
printf("File Created");
}
}
if(!(in_handle<0))
close(in_handle);
if(!(out_handle<0));
close(out_handle);
}
#include<stdio.h>
#include<stdlib.h>
int main()
{
FILE *fp1,*fp2;
char c;
fp1=fopen("source file","rb");
if(fp1==NULL)
exit(1);
fp2=fopen("destination file","wb");
if(fp2==NULL)
exit(1);
while((c=fgetc(fp1))!=EOF)
fputc(c,fp2);
fclose(fp1);
fclose(fp2);
return 0;
}
http://www.cs.bu.edu/teaching/c/file-io/intro/
#include <ctype.h>
#include <stdio.h>
#define BUFSIZE 1024
int main(int argc, char **argv)
{
charmybuf[BUFSIZE] = { 0 }, *p = NULL;
FILE *ifd = NULL, *ofd = NULL;
ifp = fopen( argv[1], “r” );
ofp = fopen( argv[2], “w” );
assert(ifp!=NULL);
assert(ofp!=NULL);
while ( ( n = fread( mybuf, sizeof(char), BUFSIZE ,ifd) ) > 0 )
{
fwrite(mybuf, sizeof(char),BUFSIZE,ofd);
}
fclose(ifd);
fclose(ofd);
return 0;
}

Resources