Hello I am writing a program that reads the contents of a binary file and prints them to the screen.
#include <stdio.h>
#include <stdlib.h> // For exit()
int main()
{
FILE *fptr;
char filename[100];
printf("Enter the filename to open \n");
scanf("%s", filename);
// Open file
fptr = fopen(filename, "rb");
if (fptr == NULL)
{
printf("Cannot open file \n");
exit(0);
}
// Read contents from file
fseek(fptr,0L,SEEK_END);
int fsize = ftell(fptr);
fseek(fptr,0L,SEEK_SET);
unsigned char *c = malloc(fsize);
fread(c,fsize,1,fptr);
fclose(fptr);
printf("%s",c);
return 0;
}
but it does not print anything.Can someone explain me why and how should I fix this problem.
What you have attempted is not at all what you wanted to achieve.
Remember printf() formats the data it prints. To be printed properly with the %s formatting, the binary data values must be ASCII values but , of course, they are not.
You should probably attempt to printf() with %d.
Related
I am writing a basic program to copy text to another text file. But in the console window after entering the filename from where text should be taken, the program ends and does not go further. How can I solve this problem?
#include <stdio.h>
#include <stdlib.h>
int main(void) {
char filename1, filename2;
FILE *infile;
FILE *outfile;
printf("Enter a data file name:");
scanf("%s", filename1);
infile = fopen("filename1", "r");
printf("Enter a input file name:");
scanf("%s", filename2);
outfile = fopen("filename2", "w");
if (infile == NULL || outfile == NULL) {
printf("Problem in opening files");
exit(0);
}
printf("files opened successfully");
char characters;
do {
characters = getc(infile);
fprintf(outfile,"%s", characters);
printf("%s", characters);
} while (!feof(infile));
fclose(infile);
fclose(outfile);
return 0;
}
There are a few problems with your program:
You are using char variables to hold names of files. These variables should be char arrays or pointers to the first char of some allocated memory.
fopen("filename2", "w") seems wrong. Although, the first argument should be a char *, you are not reading / writing the files you just asked the user to enter.
fprintf(outfile,"%s",characters) - You are using %s to print characters. This will invoke UB.
char characters - The last character of a file, the EOF character is guaranteed to fit in an int. The characters variable should be declared as an int so that it can hold the EOF character.
Here is the program that works:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
char filename1[10], filename2[10];
FILE *infile;
FILE *outfile;
printf("Enter a data file name:");
scanf("%s",filename1);
infile = fopen(filename1, "r");
printf("Enter a input file name:");
scanf("%s",filename2);
outfile = fopen(filename2, "w");
if (infile==NULL || outfile==NULL) {
printf("Problem in opening files");
exit(0);
}
printf("files opened successfully");
int characters;
/*do {
characters=getc(infile);
fprintf(outfile,"%s",characters);
printf("%s",characters);
} while(!feof(infile));
*/
while ((characters = getc(infile)) != EOF) {
fprintf(outfile, "%c", characters);
printf("%c", characters);
}
fclose(infile);
fclose(outfile);
return 0;
}
There are a number of issues.
char filename1, filename2;
This only allows filename1 and filename2 to hold a single char - not a C string. You need to reserve memory as a char array. Like:
char filename1[64], filename2[64]; // Allow 63 chars for file name
Then
scanf("%s",filename1);
is really bad as it allows the user to overflow your input buffers. Consider using fgets or at least do:
scanf("%63s",filename1); // Limit user input to 63 chars as the buffer is 64
// The "last" char is for the string termination
Then the loop:
First, characters shall be int so that you can check for EOF. Further, check directly on getc instead of using feof. And don't use %s for printing a single char to the output file - use %c. Like
int characters;
while(1) {
characters=getc(infile);
if (characters == EOF) break; // Break (aka jump out of the loop) on
// end-of-file or errors
fprintf(outfile,"%c",characters); // %c instead of %s
// or use: putc(characters, outfile)
// instead of fprintf
printf("%s",characters);
}
This is my code which I have written so far
#include <stdio.h>
#include <string.h>
#include <stdlib.h> // For exit()
int main()
{
FILE *fptr1, *fptr2;
char filename[100], c;
char quit[4] = "exit";
// char *filearray[100];
char filearray[100][14];
FILE **originalfilearray;
int counter = 0;
//Copy part
while(1){
printf("Enter the filename to open for reading \n");
scanf("%s", filename);
fptr1 = fopen(filename, "r");
if (fptr1 == NULL)
{
break;
printf("Cannot open file %s \n", filename);
exit(0);
}
strcpy(filearray[counter], filename);
originalfilearray[counter] = fptr1;
counter+=1;
}
//Paste part
for (int i = 0; i < counter; i++)
{
printf("Enter the filename to open for writing for file %s\n", filearray[i]);
scanf("%s", filename);
fptr2 = fopen(filename, "w");
// Read contents from file
c = fgetc(fptr2);
while (c != EOF)
{
fputc(c, fptr2);
c = fgetc(originalfilearray[i]);
}
printf("\nContents copied to %s\n", filename);
}
}
The problem occurs when I run the paste code the file is created but no content is pasted.
I have already tried reading many post regarding array of pointers of file. Some suggested to create originalfilearray variable with a single pointer some with double.
The major problem I guess is with the copy part.
Can someone please help me with the part where I need to copy the data of multiple files in the originalfilearray variable
Thank You
Apart from not allocating memory for originalfilearray, which other user explained, here are some things you are doing wrong
In
c = fgetc(fptr2);
You are trying to get character from an empty file you just opened in
fptr2 = fopen(filename, "w");
what you should be doing is starting a file pointer fptr and opening
FILE *fptr=fopen(filearray[i], "r");
and then copying content into it with
while ((c = fgetc(fptr))!= EOF)
{
fputc(c, fptr2);
}
The code is running well, it's just that I feel there are still many mistakes and give me a little direction to improve in the future. I want to learn how to maintain the code properly.
fix the code as it should!
Data.txt
[1] Line numbers 1.
[2] Line numbers 2.
[3] Line numbers 3.
[4] Line numbers 4.
[5] Line numbers 5.
[6] Line numbers 6.
My code:
#include <stdio.h>
#include <stdlib.h>
int getLengthFile(char *namafile)
{
FILE *fptr;
int n =0;
fptr = fopen(namafile, "r");
if(fptr != NULL){
char c;
while((c = getc(fptr)) != EOF) {
++n;
}
fclose(fptr);
}
return n;
}
int main(){
FILE *fptr;
int i;
fptr = fopen("Data.txt","r");
if(fptr != NULL){
printf("Succes reads file!\n");
if(getLengthFile("Data.txt")>0){
char strLine[225];
while(fgets(strLine,225,fptr) != NULL){
printf("%s",strLine);
}
}else{
printf("File is empty!\n");
}
fclose(fptr);
}else{
printf("Error reads file!\n");
}
return 0;
}
Here is a more or less fixed version of the code presented in the first edition of the question, where the getLengthFile() function was not present. In my opinion, that function does not provide useful functionality. If you must report that the file contained no data, you could do so by counting the number of times fgets() returns any data — if it returns any data, the file was not empty.
#include <stdio.h>
int main(void)
{
const char filename[] = "Data.txt";
FILE *fptr = fopen(filename, "r");
if (fptr == NULL)
{
fprintf(stderr, "Error opening file %s for reading!\n", filename);
return 1;
}
printf("Success opening file %s for reading\n", filename);
char strLine[225];
while (fgets(strLine, sizeof(strLine), fptr) != NULL)
printf("%s", strLine);
fclose(fptr);
return 0;
}
When there is no file Data.txt, example output is:
Error opening file Data.txt for reading!
When there's a file containing one short line of data, example output is:
Success opening file Data.txt for reading
data from the file Data.txt
I also tested it on a file with longer lines, including lines with as many as 380 characters, and the output from the program was the same as the input except for the line saying 'Success opening file Data.txt for reading'.
My goal is to be able to write a string to a file and have the whole thing show up, and not just part of it. The problem is that when i check into my text file there is a few charters left off of the string that i typed in.
Here is My code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp = fopen("file.txt", "w");
if (fp == NULL)
{
printf("Error opening file!\n");
exit(1);
}
char comment[100];
fp=fopen("/home/matthew/Desktop/BBE.txt","w");
printf("Enter, String: ");
scanf("%s", &comment);
fgets(comment, sizeof comment, stdin);
fputs(comment,fp);
}
And the input that i want in my text file is this:
Enter, String: Hello World
But when i check my text file i get this:
World
I am missing a word here and have no idea why, please help.
Get rid of the scanf, as it is reading in the first word of your input, so your code looks like this:
char comment[100];
fp=fopen("/home/matthew/Desktop/BBE.txt","w");
printf("Enter, String: ");
fgets(comment, sizeof comment, stdin);
fputs(comment,fp);
You are reading the input from the user using both fgets and scanf. You don't need both. Also, in your scanf, you are passing the address of the address of the first element of the character array instead of just the address of the first element (use 'comment' instead of '&comment' in your scanf). You are also not closing the File after write. Try following:
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp = fopen("/home/matthew/Desktop/BBE.txt", "w");
if (fp == NULL)
{
printf("Error opening file!\n");
exit(1);
}
char comment[100];
fp=fopen("file.txt","w");
printf("Enter, String: ");
scanf("%s", comment); //Don't pass &comment. Just pass 'comment' - the addr of zeroth element.
//fgets(comment, sizeof comment, stdin);
fputs(comment,fp);
fclose(fp);
}
Why are you using two files here when you've to write the input from stdin in one of the file? Below piece of code will help you get the desired output. Better to use gets() here instead of fgets() as you're not reading input from file. Also, don't forget to close the files when you're done. Hope this helps!!
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
FILE *fp;
char comment[100] = {0};
fp=fopen("tempfile.txt","w");
if (fp == NULL)
{
printf("Error opening file!\n");
exit(1);
}
printf("Enter String: ");
gets(comment);
fwrite(comment, sizeof(comment), 1, fp) ;
fclose(fp);
return 0;
}
How i can make a new line at the end of a file to fprintf() user inputed text?
My code right now is this:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int lines;
int number;
FILE *fp;
printf("Insert random number: ");
scanf("%d", &number);
fp = fopen("textfile.txt", "r");
char ch;
while((ch=fgetc(fp))!=EOF)
{
if (ch=='\n') {
lines++;
}
}
fclose(fp);
fopen("textfile.txt", "ab");
fseek(fp, lines, SEEK_SET);
fprintf(fp,"%d", number);
fclose(fp);
}
You just need to add a '\n' to the fprintf() like this
fprintf(fp,"\n%d", number)
/* ^ */
but you also need a lot of error checking, for instance fopen() returns NULL when it fails to open the file.
Your code is actually very broken, you count the lines in the file opened with "r", i.e. for reading, then you call fopen() with "ab" but discard the return value, you then fseek() the number of lines, and fseek() is for the number of characters not lines, then you write to the closed fp pointer, because
fopen("textfile.txt", "ab"); /* you don't assign the return value anywhere */
fseek(fp, lines, SEEK_SET); /* this is the same pointer you `fclosed()' */
/* ^ this will not seek to the end of the file */
fprintf(fp,"%d", number); /* here `fp' is still invalid */
Test this
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *file;
const char *filename = "textfile.txt";
printf("Insert a number: ");
if (scanf("%d", &number) != 1)
{
fpritnf(stderr, "invalid input, expected a number\n");
return -1;
}
file = fopen(filename, "a");
if (file == NULL)
{
fprintf(stderr, "cannot open %s for appending\n", filename);
return -1;
}
fprintf(file, "\n%d", number);
fclose(file);
return 0;
}
You don't need to fseek() if you open with "a" because new content is appended to the end of the file, you need a '\n' before the user input if there was no '\n' in the file or if you want to force the new value in a new line.
You don't need the "b" in the mode string, because you are writing text to the file, and on some platforms the file will have issues when you open it in a text editor.