Im trying to copy a mal file to a text file. So basically I want the contents of the mal file to copy over to the text file. the mal file is name test1.mal and the txt file is name output.txt. This is what I have but it keeps printing out error reading the file.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
char content[255];
char newcontent[255];
FILE *fp1, *fp2;
fp1 = fopen("test1.mal", "r");
fp2 = fopen("output.txt", "w");
if(fp1 == NULL || fp2 == NULL)
{
printf("error reading file\n");
exit(0);
}
printf("files open correct\n");
while(fgets(content, sizeof (content), fp1) !=NULL)
{
fputs(content, stdout);
strcpy (content, newcontent);
}
printf("%s", newcontent);
printf("text received\n");
while(fgets(content, sizeof(content), fp1) !=NULL)
{
fprintf(fp2, newcontent);
}
printf("file created and text copied");
fclose(fp1);
fclose(fp2);
return 0;
}
The posted code has several problems, many of which are expressed in the comments to the OP's question.
The following code is one way to perform the desired operation.
It cleanly compiles and performs appropriate error checking
Note: the calls to perror() will output, to stderr, the enclosed text and the reason the OS thinks the operation failed.
Note: used open(), close(), read(), write() because there is no guarantee that the input .mal file does not contain embedded NUL characters.
#include <stdio.h> // perror()
#include <stdlib.h> // exit(), EXIT_FAILURE
#include <unistd.h> // read(), write(), close()
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h> // open()
// declare the size of the buffers with a meaningful name
// do not use 'magic' numbers
#define BUFF_SIZE 255
int main(void)
{
char content[ BUFF_SIZE ];
int fin;
int fout;
if( 0 > (fin = open("test1.mal", O_RDONLY) ) )
{
perror( "open for read of test1.mal failed" );
exit( EXIT_FAILURE );
}
// implied else, open successful
if( 0 > (fout = open("output.txt", O_WRONLY) ) )
{
perror( "open for write of output.txt failed");
close( fin );
exit( EXIT_FAILURE );
}
// implied else, fopen successful
printf("files open correct\n");
ssize_t readCount;
while( 0 < (readCount = read( fin, content, sizeof( content) ) ) )
{
//fputs(content, stdout); // are you sure the file contents are printable?
if( readCount != write( fout, content, (size_t)readCount ) )
{ // then write error occured
perror( "write of data to output file failed" );
close( fin );
close( fout );
exit( EXIT_FAILURE );
}
// implied else, write successful
}
if( 0 > readCount )
{ // then read error occurred
perror( "read of file failed" );
close( fin );
close( fout );
exit( EXIT_FAILURE );
}
// implied else, complete file copied
printf("file created and text copied\n");
close( fin );
close( fout );
return 0;
} // end function: main
Related
I am trying to write multiple structures in a .DAT file. But after writing it, I am not getting correct values of struct 1, while struct 2 is not able to be find by read function.
Please let me know the solution.
static const char fileName[] = "file.dat";
struct abc
{
int variable;
}ptr1;
ptr1.variable = 5;
struct xyz
{
int variable;
}ptr2;
ptr2.variable = 6;
int write_file_testing()
{
FILE *outfile;
outfile = fopen(fileName, "a");
if (outfile == NULL) return -1;
fwrite(&ptr1, sizeof(struct abc), 1, outfile);
fwrite(&ptr2, sizeof(struct xyz), 1, outfile);
fclose(outfile);
return 0;
}
int read_file_testing()
{
FILE *infile;
infile = fopen(fileName, "r");
if (infile == NULL)
{
fprintf(stderr, "\nError opening file\n");
exit(1);
}
while (fread(&ptr1, sizeof(struct abc), 1, infile))
{
printf("Variable = %d\n", ptr1.variable);
}
while (fread(&ptr2, sizeof(struct xyz), 1, infile))
{
printf("Variable = %d\n", ptr2.variable);
}
fclose(infile);
return 0;
}
the following proposed code:
is a minimal complete example
cleanly compiles
performs the desired functionality
properly handles I/O errors
opens the file for output with the "w" mode rather than the "a" mode so starts with a clean file
eliminates the duplicate struct definition and usage
documents why each header file is included
and now, the proposed code:
#include <stdio.h> // fopen(), fclose(), fread(), fwrite(), perror()
#include <stdlib.h> // exit(), EXIT_FAILURE
void write_file_testing( void );
void read_file_testing( void );
static const char fileName[] = "file.dat";
struct abc
{
int variable;
};
struct abc ptr1[2];
int main( void )
{
write_file_testing();
read_file_testing();
}
void write_file_testing()
{
FILE *outfile;
outfile = fopen(fileName, "w");
if (outfile == NULL)
{
perror( "fopen to write to file.dat failed" );
exit( EXIT_FAILURE );
}
ptr1[0].variable = 5;
ptr1[1].variable = 6;
if( fwrite(&ptr1[0], sizeof(struct abc), 1, outfile) != 1)
{
perror( "fwrite for first instance of struct failed" );
fclose( outfile );
exit( EXIT_FAILURE );
}
if( fwrite(&ptr1[1], sizeof(struct abc), 1, outfile) != 1 )
{
perror( "fwrite for second instance of struct failed" );
fclose( outfile );
exit( EXIT_FAILURE );
}
fclose(outfile);
}
void read_file_testing()
{
FILE *infile;
infile = fopen(fileName, "r");
if (infile == NULL)
{
perror( "fopen to read file.dat failed" );
exit( EXIT_FAILURE );
}
if( fread(&ptr1[0], sizeof(struct abc), 1, infile) == 1 )
{
printf("Variable = %d\n", ptr1[0].variable);
}
if( fread(&ptr1[1], sizeof(struct abc), 1, infile) == 1 )
{
printf("Variable = %d\n", ptr1[1].variable);
}
fclose(infile);
}
a successful run of the program results in:
Variable = 5
Variable = 6
Simple question.
When I try to open a file with the name text.txt it works properly.
However if I rename the file to text.cir.txt it gives me ERROR.
What can I do to fix it?
FILE *fd;
char nome_fich[] = "text.cir.txt";
int x;
fd = fopen("text.cir.txt", "r");
if (fd == NULL)
{
printf("ERROR");
}
else
{
while ((x = fgetc(fd)) != EOF)
{
printf("%c", x);
}
fclose(fd);
}
the following proposed code:
cleanly compiles
performs the desired functionality
properly checks for and handles errors
and now, the proposed code:
#include <stdio.h> // FILE, fopen(), perror(), printf()
#include <stdlib.h> // exit(), EXIT_FAILURE
int main( void )
{
FILE *fd = fopen( "text.cir.txt", "r" );
if ( !fd )
{
perror( "fopen failed" );
exit( EXIT_FAILURE );
}
// implied else, fopen successful
int x;
while ((x = fgetc(fd)) != EOF)
{
printf("%c", x);
}
fclose(fd);
}
when run against any .txt file, it performs the desired operation.
Note: I'm running Linux version 18.04
I was assigned a program to write that uses file system calls to take a command line argument(assuming you pass in a text file address) and return the contents of said file. I have this code so far, but can't seem to figure out why my compiler is giving me errors in terms of recognizing the text-file passed as an argument, along with printing the information received from the file. Any sort of assistance/help is greatly appreciated.
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
int main(int argc, char *argv[]){
int FP;
ssize_t bytes;
char buffer [100];
if(argc == 1){
FP = open(argv[1], O_RDONLY);
printf("Program name is : %s", argv[0])
bytes = read(FP, buffer,sizeof(buffer) -1);
printf("%s", bytes);
close(FP);
}
return 0;
}
the following proposed code:
incorporates the comments to the question
implements the desired functionality
proper checks for errors
documents why the header files are being included. In general, if you cannot state why a header file is being included, then don't include it. (the compiler will then tell you if you actually need that header file, and why
when compiling always enable the warnings, then fix those warnings. (for gcc, at a minimum use: -Wall -Wextra -pedantic -Wconversion -std=gnu11 )
and now, the proposed code.
#include <stdio.h> // fopen(), perror(), fgets(), fprintf(), printf(), FILE
#include <stdlib.h> // exit(), EXIT_FAILURE
#define MAX_INPUT_LEN 100
int main(int argc, char *argv[])
{
FILE *fp;
char buffer [ MAX_INPUT_LEN ];
if(argc != 2)
{
fprintf( stderr, "USAGE: %s fileName\n", argv[0] );
exit( EXIT_FAILURE );
}
// implied else, correct number of command line parameters
printf( "Program name is : %s", argv[0] );
printf( "file to read: %s\n", argv[1] );
fp = fopen( argv[1], "r" );
if( NULL == fp )
{
perror( "fopen failed" );
exit( EXIT_FAILURE );
}
// implied else, fopen successful
while( NULL != fgets( buffer, sizeof buffer, fp ) )
{
printf( "%s", buffer );
}
fclose( fp );
return 0;
}
im trying to read a file and write the content in other file, but the finish file is empty after program execution.
this is the code:
char buf[80];
int main(int argc, char *argv[])
{
int fd;
int fs;
if( (fd=open("salida.txt",O_CREAT|O_TRUNC|O_WRONLY,S_IRUSR|S_IWUSR))<0) {
printf("\nError %d en open",errno);
perror("\nError en open");
exit(EXIT_FAILURE);
}
if( (fs=open(argv[1],O_CREAT|O_TRUNC|O_RDONLY,S_IRUSR|S_IWUSR))<0) {
printf("\nError %d en open",errno);
perror("\nError en open");
exit(EXIT_FAILURE);
}
int cont = 1;
if(fs=read(fd,&buf,80) < 0){
cont++;
if(write(fd,&buf,80) != 80) {
perror("\nError en el write");
exit(EXIT_FAILURE);
}
}
The condition
if (fs=read(fd,&buf,80) < 0)
doesn't mean
if ((fs = read(fd,&buf,80)) < 0)
it means
if (fs = (read(fd,&buf,80) < 0))
and has the effect of overwriting the file descriptor fs with 0 if the read succeeds, and with 1 if it fails. (read returns the number of bytes read, or -1 on failure.)
You don't want to assign the result to fs in any case, as it means that you're destroying any possibility of writing to the file you opened.
Also, fd is apparently your output file, so it's slightly strange to read from it.
If you want to copy (up to) 80 bytes, you could say something like
int size = 0;
if((size = read(fs, buf, 80)) > 0){
if (write(fd, buf, size) != size) {
perror("\nError en el write");
exit(EXIT_FAILURE);
}
}
Also, truncating the input file (O_TRUNC) may not be the best idea.
You seem to be reading and writing from and to fd. Your code is not very clear, you may want to clean it up. As other answers have pointed out, there are multiple errors in your code and your intentions are not entirely clear.
You should comment your code and indent properly.
int main()
{
char ch;
FILE *source, *target;
source = fopen(source_file, "r");
if( source == NULL )
{
printf("Press any key to exit...\n");
exit(EXIT_FAILURE);
}
target = fopen(target_file, "w");
if( target == NULL )
{
fclose(source);
printf("Press any key to exit...\n");
exit(EXIT_FAILURE);
}
while( ( ch = fgetc(source) ) != EOF )
fputc(ch, target);
printf("File copied successfully.\n");
fclose(source);
fclose(target);
return 0;
}
You never closed the files. Most operating systems don't actually make changes to the files until you close them. Until then your changes are only visible in RAM and not on the hard drive. Just add:
close(fd);
close(fs);
To the end of your code.
There seem to be some other problems too (why are you reading from a write-only file and seemingly attempting to write the same data back to it), and it's very much unclear what you're trying to accomplish.
// the following compiles, but the #include statements do expect linux
// so if your using a different OS, you may have to update them.
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#include <errno.h>
#define BUFFER_SIZE (80)
static char buf[ BUFFER_SIZE ]; // static so only visible in this file
// note: file scope variables are set to 0 by the startup code
int main( int argc, char *argv[])
{
int fd = -1; // destination file descriptor
int fs = -1; // source file descriptor
int statusRd = 0; // returned value from read
int statusWr = 0; // returned value from write
if( 2 > argc )
{ // then, file name parameter missing
printf( "\ncalling format: %s <filenametoread>\n", argv[0]);
exit( EXIT_FAILURE );
}
// implied else, proper number of parameters
// note: there should be a call to 'stat()'
// to assure input file exists placed here
// open destination file, uses fixed name
if( (fd = open("salida.txt", O_TRUNC | O_CREAT | O_WRONLY, S_IWRITE) ) <0)
{
printf("\nError %d en open",errno);
perror("open for write failed");
exit(EXIT_FAILURE);
}
// implied else, open of destination file successful
if( (fs=open(argv[1],O_RDONLY,S_IREAD))<0)
{
printf("\nError %d en open",errno);
perror("open for read failed");
close(fd); // cleanup
exit(EXIT_FAILURE);
}
// implied else, open of source file successful
do
{
if( (statusRd = read(fs,&buf, BUFFER_SIZE)) < 0)
{ // then read failed
perror( "read failed" );
close(fs); // cleanup
close(fd); // cleanup
exit( EXIT_FAILURE );
}
// implied else, read successful
if( 0 < statusRd )
{ // then some bytes read
if( ( statusWr = write(fd, buf, statusRd)) < 0)
{ // then, write failed
perror("\nwrite failed");
close(fs); // cleanup
close(fd); // cleanup
exit(EXIT_FAILURE);
}
}
} while( statusRd > 0 ); // exit loop when reach end of file
close(fs);
close(fd);
return(0);
}
Hello i want to dynamically initialize an array based on a text file, but for some reason im doing it wrong. i get an error at line "malloc" that the "texto" is not being initialized.
char nome[] = "partidas.txt";
f = fopen(nome, "rt");
int size = fsize(f);
char **texto;
**texto = (char)malloc(size);
int i = 0;
while ((fgets(texto[i], sizeof(texto), f) != NULL))
{
printf("%s\n", texto[i++]);
}
//remember to include the right header files
#include <stdio.h>
#include <string.h>
#include <errno.h>
#define READ_LENGTH 1024
char* pFileContents = NULL;
int iContentsIndex = 0;
long int sz = 0;
FILE* pFD = NULL;
int readCount = 0;
int stat = 0;
// note: all errors are printed on stderr, success is printed on stdout
// to find the size of the file:
// You need to seek to the end of the file and then ask for the position:
pFD = fopen( "filename", "rt" );
if( NULL == pFD )
{
perror( "\nfopen file for read: %s", strerror(errno) );
exit(1);
}
stat = fseek(pFD, 0L, SEEK_END);
if( 0 != stat )
{
perror( "\nfseek to end of file: %s", strerror(errno) );
exit(2);
}
sz = ftell(pFD);
// You can then seek back to the beginning
// in preparation for reading the file contents:
stat = fseek(pFD, 0L, SEEK_SET);
if( 0 != stat )
{
perror( "\nfseek to start of file: %s", strerror(errno) );
exit(2);
}
// Now that we have the size of the file we can allocate the needed memory
// this is a potential problem as there is only so much heap memory
// and a file can be most any size:
pFileContents = malloc( sz );
if( NULL == pFileContents )
{
// handle this error and exit
perror( "\nmalloc failed: %s", strerror(errno) );
exit(3);
}
// then you can perform the read loop
// note, the following reads directly into the malloc'd area
while( READ_LENGTH ==
( readCount = fread( pFileContents[iContentsIndex], READ_LENGTH, 1, pFD) )
)
{
iContentsIndex += readCount;
readCount = 0;
}
if( (iContentsIndex+readCount) != sz )
{
perror( "\nfread: end of file or read error", strerror(errno) );
free( pFileContents );
exit(4);
}
printf( "\nfile read successful\n" );
free( pFileContents );
return(0);