implementing copy command using file my code is copying garbage? - c

Implementing copy command using file my code is copying garbage.please help me to fix
#include<stdio.h>
int main()
{
char ch;
FILE *fp,*fp1;
fp=fopen("source","r");
if(fp==NULL)
{
printf("no file\n");
return;
}
else
{
printf("file is present\n");
fp1=fopen("dest","w");
while(ch=fgetc(fp)!=EOF)
fputc(ch,fp1); // why source contain is not copyed to dest?
}
fclose(fp);
fclose(fp1);
}

while(ch=fgetc(fp)!=EOF)
is eqivalent to:
while(ch = (fgetc(fp)!=EOF))
thus gives ch values either 1 or 0 depending on whether fgetc(fp)!=EOF) is true. What you want is:
while((ch = fgetc(fp)) != EOF)

Related

Changing the periods in my file to exclamation points, and saving the full text to a new file

In a file I made, practice.txt, I have a few sentences that end with (.), I want to rewrite everything to a different file, but change all the periods to exclamation points.
#include <stdlib.h>
#include <stdio.h>
int main() {
FILE *fp = fopen("practice.txt", "r");
FILE *fp2 = fopen("practice_!.txt", "w");
if (fp == NULL)
return -1;
int c;
while ((c = fgetc(fp)) != EOF) {
if (c == '.') {
c = '!';
}
fputc(c, fp2);
}
fclose(fp);
fclose(fp2);
return 0;
}
This code doesn't seem to be outputting anything to the new file.
You should test if both files wre open successfully and output a meaningful message if not. If your program fails to open the input file, it creates or truncates the output file and exits silently. This might explain be what you observe. Are you sure you run the program from the directory where the input file was created?
The copying and substitution code seems OK.
Here is a modified version:
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
FILE *fp = fopen("practice.txt", "r");
if (fp == NULL) {
fprintf(stderr, "cannot open %s: %s\n",
"practice.txt", strerror(errno));
return 1;
}
FILE *fp2 = fopen("practice_!.txt", "w");
if (fp2 == NULL) {
fprintf(stderr, "cannot open %s: %s\n",
"practice_!.txt", strerror(errno));
return 1;
}
int c;
while ((c = fgetc(fp)) != EOF) {
if (c == '.') {
c = '!';
}
fputc(c, fp2);
}
fclose(fp);
fclose(fp2);
return 0;
}
The Un*x way to write that program, is a filter (basically a program that reads from stdin and writes to stdout)
#include <stdio.h>
int main(void) {
int c;
while ((c = getchar()) != EOF) {
if (c == '.') c = '!';
putchar(c);
}
return 0;
}
and you'd use it as
executable <practice.txt >practice_!.txt
You code is correct.
If the file was not opened, you'd get a segmentation fault since either fp or fp2 would then be NULL.
So... the only thing I can think of is that you're hunting a red herring.
Possibilities that come to mind:
you're actually executing an old version of the executable file.
you're on a Unix console (e.g. Linux), and you did not escape the "!" which is a shell special character. For example I managed to get this just now on my bash:
$ cat practice_!.txt # I should have enclosed the name in single quotes
cat practice_.txt
cat: practice_.txt: No such file or directory
(The file "practice_!.txt" does exist; "practice_.txt" does not).

Replacing specific text of a file in C

Alright, so basically what I have to do is change all the numbers of a text file to dollar sign, I know how to scan for the specific character but I am stuck on how to replace that specific character with dollar sign. I don't want to use fseek or any library commands, how do I proceed and why isn't my code working?
#include<stdio.h>
main()
{
FILE* fptr;
char filename[50];
char string[100];
int i;
printf("Enter the name of the file to be opened: ");
scanf("%s",filename);
fptr=fopen(filename,"w");
if(fptr==NULL)
{
printf("Error occurred, try again.");
return 0;
}
fgets(string,"%s",fptr);
do
{
if(string[i]>='1' && string[i]<='9')
{
string[i]='$';
}
}
while(i!=100);
fclose(fptr);
}
There are basically two approaches at first glance, the first is to use fseek() and the second to read the file in its entirety and replace the characters to your criteria and finally write that in one shot. You can choose either of the approaches depending on your need. For large file you should prefer the former and for small file you can prefer the latter.
Here's an example code of the former:
#include <stdio.h>
int main() {
// Open the file
FILE *fptr = fopen("input.txt", "r+");
if (!fptr) {
printf("Error occurred, try again.");
return -1;
}
int c;
// Iterate through all characters in a file
while ((c = getc(fptr)) != EOF) {
// Check if this current character is a digit?
if (c >= '0' && c <= '9') {
// Go one character back
if (fseek(fptr, -1, SEEK_CUR) != 0) {
fprintf(stderr, "Error while going one char back\n");
return -1;
}
// Replace the character with a '$'
if (fputc('$', fptr) == EOF) {
fprintf(stderr, "Error while trying to replace\n");
return -1;
}
}
}
// Flush the changes to the disk
if (fflush(fptr) != 0) {
fprintf(stderr, "Error while flushing to disk\n");
return -1;
}
// Close the file
fclose(fptr);
return 0;
}

Extra character at end while copying?

This is making me nuts I am trying to make a simple program to copy any type of file using the following code but the result I get is unexpected (one or two extra characters at the end of copied file?). For instance if my original file has This is an example the copied file contains This is an exampleÿ
CODE
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp,*fpp;
char pbuff, fname[32];
int i;
printf(" FILE NAME TO OPEN : ");
scanf(" %32s", fname);
fp = fopen(fname, "rb");
fpp = fopen("file", "wb");
if(fp==NULL)
{
printf("NO SUCH FILE. EXITING NOW.");
getch();
exit(1);
}
while(!feof(fp))
{
pbuff = fgetc(fp);
fputc(pbuff, fpp);
}
printf("SUCCESSFULLY CREATED!");
fclose(fp);
fclose(fpp);
getch();
return(0);
}
Can anyone help me out with this one? I will be really very thankful.
The reason is that feof (like most end-of-file indicators in most languages/environments) is only set AFTER the end-of-file has been reached. Since you write the character and only then check the EOF status, you're writing 1 too many characters. fgetc's return value is a predefined EOF if the end-of-file was reached during the call.
You could solve that in 1 of 2 ways:
while(true)
{
pbuff = fgetc(fp);
if(feof(fp))
break;
fputc(pbuff, fpp);
}
Or: (edit as melpomene correctly noticed!)
// Change pbuff to type int in the declartion, and then...
while(true)
{
pbuff = fgetc(fp);
if(EOF == pbuff)
break;
fputc(pbuff, fpp);
}

Struct sscanf not working as it should?

i am trying to sipmply input some data into a struct from a file.
I have used the same excact code in a different program and it works as it should?
I dont know where i am wrong.
Shouldnt the code below work ? Maybe i am not that familiar with sscanf .I would like some help. Thank you.
The txt file is like this:
foo.var 1241
poa.org 421
aeraf.gr 5456
oiggdf.po 98843
Code:
struct filedata
{
char fname[50];
int fsize;
};
int main()
{
char line[60];
int i=0;
int numberoffiles=0;
int lines=0;
int ch=0;
FILE *fp = fopen("mytext.txt","r");
while ((ch = fgetc(fp)) != EOF)
{
if (ch == '\n')
lines++;
}
struct filedata file[lines];
numberoffiles=lines + 1;
if(fp == (FILE*)NULL)
{
fprintf(stderr,"Cannot Open File\n");
exit (-1);
}
else
{
while (fgets(line,60,fp)!=NULL)
{
sscanf(line,"%s %d",file[i].fname,&file[i].fsize);
i++;
}
}
}
Your loop that counts the number of lines reads the entire file so that the current position is at the end of the file when you begin your second loop. Consider using rewind() before your second loop to move back to the start of the file.
Also, your test to see if fp is NULL should go right after the open() call. Otherwise, your code that reads the number of lines will fail.

How to create a file for use in c?

I have a program:
#include <stdio.h>
#include <string.h>
// ne menuvaj ovde
void wtf() {
FILE *f = fopen("text.txt", "w");
char c;
while((c = getchar()) != EOF) {
fputc(c, f);
}
fclose(f);
}
int main() {
wtf();
FILE *vlezna;
vlezna=fopen("text.txt","r");
float words=0,lines=0,average=0;
int counter=0;
char ch;
while((ch=fgetc(vlezna))!=EOF)
{
if(ch==' ')
words++;
if(ch=='\n');
{
words++;lines++;
}
}
average=words/lines;
printf("%f",average);
fclose(vlezna);
vlezna=fopen("text.txt","r");
while((ch=fgetc(vlezna))!=EOF)
{ words=0;
if(ch==' ')
words++;
if(ch=='\n')
{
words++;
if(words<average) counter++;
}
}
fclose(vlezna);
printf("%d",counter);
}
So i presume the first function writes to the file. But i guess the file should be created first, and i don't know how(except with right click new text document).
Also i didn't know how to return the pointer at the beginning of the file so i closed it and opened it again presuming that that will return the pointer at the beginning?
fopen create the file if it does not exist if option is "w".
Read the documentation here : http://www.cplusplus.com/reference/cstdio/fopen/
There is no need to create. For the man page of fopen:
``w'' Truncate to zero length or create text file for writing. The stream is positioned at the
beginning of the file.
To set the file pointer use fseek. However, to read and write you need different open flags.

Resources