C File Name with multiple periods - c

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

Related

Executable fails to open files when double clicked

I have a C file called fileTest.c, which simply contains this:
#include <stdio.h>
int main()
{
FILE* file = fopen("test.txt","r");
if (file == NULL) {
printf("file failed to open\n");
}
fclose(file);
return 0;
}
In the same directory, I have the test.txt file, which is empty.
I compile like so: gcc -Wall -std=gnu99 fileTest.c -o fileTest
Everything works perfectly (nothing is printed) if I run the resultant executable in the command line with ./fileTest, but when I try to run the executable by double clicking the exec file, I get "file failed to open". I'm using macOS High Sierra 10.13.3. Why is this happening?
You need to provide the full path of the file "test.txt".
I tested it on the macOS High Sierra 10.13.2 with g++ 5.5.0. This is the output
the following proposed code:
outputs the current working directory path
handles any error on the call to fopen()
outputs a message if the call to fopen() is successful
handles any error on the call to getcwd()
and now the proposed code:
#include <stdio.h>
#include <unistd.h>
int main( void )
{
char pathName[1024];
if( !getcwd( pathName, sizeof( pathName ) )
{
perror( "getcwd failed" );
exit( EXIT_FAILURE );
}
// implied else, getcwd successful
printf( "current working Directory: %s\n", pathName );
FILE* file = fopen("test.txt","r");
if (file == NULL)
{
perror("file failed to open\n");
exit( EXIT_FAILURE );
}
// implied else, fopen successful
printf( "call to fopen successful\n" );
fclose(file);
return 0;
}
However, it does not effect your question about why double clicking the executable does not cause the executable to be executed.

a program that takes one command line argument and outputs the contents of the file to standard out.

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

copying files in C program?

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

Why is fopen not working?

I can't figure out why this isn't working.
#include <stdio.h>
int main(void) {
FILE *in, *out;
// char *FULLPATH = "C:\\Users\\Jay\\c\\workspace\\I-OFiles\\in.txt\\ ";
// char *mode = "r";
// in = fopen(FULLPATH, mode);
//
// if (in == NULL) {
// perror("Can't open in file for some reason\n");
// exit (1);
// }
out = fopen("C:\\Users\\Jay\\c\\workspace\\I-OFiles\\out.txt", "w");
if (out == NULL) {
perror("Can't open output file for some reason \n");
exit(1);
}
fprintf(out, "foo U");
fclose(in);
fclose(out);
return 0;
}
if I remove the // from the commented lines, the error compiler gives is
: Invalid argument
I don't understand why (I read all the other threads related, and nothing).
It does actually write the out.txt file OK, so it doesn't seem like a path misspelled problem.
Remove backslash after in.txt.
The input file name seems bogus:
"C:\\Users\\Jay\\c\\workspace\\I-OFiles\\in.txt\\ "
The filename is just a single space " " and in.txt is probably not a directory.
Change the code to:
const char *FULLPATH = "C:\\Users\\Jay\\c\\workspace\\I-OFiles\\in.txt";
Or preferably:
const char *FULLPATH = "C:/Users/Jay/c/workspace/I-OFiles/in.txt";
for better portability as forward slashes work in Windows as well as in Unix.
Furthermore, it is easy to provide more information as to why fopen() failed to open the files.
Here is a modified version:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
FILE *in, *out;
in = fopen("C:/Users/Jay/c/workspace/I-OFiles/in.txt", "r");
if (in == NULL) {
perror("Cannot open input file");
exit(1);
}
out = fopen("C:/Users/Jay/c/workspace/I-OFiles/out.txt", "w");
if (out == NULL) {
fclose(in);
perror("Cannot open output file");
exit(1);
}
fprintf(out, "foo U");
fclose(in);
fclose(out);
return 0;
}
Change backslash to slash.
Maybe you don't have permissions or something like that.
out = fopen("C://Users//Jay//c//workspace//I-OFiles//out.txt", "w");
if (!out)
perror("fopen");
return 0;

why write function isn't working?

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

Resources