Writing string to a .mc file - c

I'm trying to write data to a file and it's not appearing but I know the program is finishing. I establish a writable file getting the name from a command argument
FILE *outFilePtr;
Then I create the file through:
outFilePtr=fopen(outFileString,"w"); //outFileString is the name of the file from command
Now I attempt to print to this file which has a .mc extension:
fprintf(outFilePtr,"%s\n","1001") //example string
The file gets created and nothing is written to it. This is probably a dumb question but can you not write strings to machine code files? I'm trying to find a solution to this problem if that's the case.

You should check the results of fopen and fprintf. This works for me:
#include <stdio.h>
#include <errno.h>
int
main(int argc, char *argv[])
{
FILE *outFilePtr;
outFilePtr = fopen("asdf.mc", "w");
if(!outFilePtr) {
perror("Couldn't open it");
fprintf(stderr, "errno: %d\n", errno);
exit(-1);
}
if(fprintf(outFilePtr, "%s\n", "1001") < 0)
{
fclose(outFilePtr);
perror("Couldn't write to it");
fprintf(stderr, "errno: %d\n", errno);
exit(-1);
}
fclose(outFilePtr);
}
If there is a problem opening the file (permissions, etc), perror will show it. For example, using an empty string for the filename gave me this in a window$ machine:
Couldn't open it: Invalid argument
errno: 22
If I close outFilePtr before the fprintf, this error gets displayed:
Couldn't write to it: Bad file descriptor
errno: 9

please check that you close the file(using fclose(fptr)) after fprintf()..

Related

Why cannot I read string by fgets in C programming language?

I have this code work :
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
FILE *File_fp = fopen("Example.dat", "w");
char Temporary[50];
if(!File_fp)
{
printf("An error occurred while creating the file.\n");
exit(1);
}
fprintf(File_fp, "This is an example.\n");
fgets(Temporary, 49, File_fp);
printf("It was \"%s\"\n", Temporary);
return EXIT_SUCCESS;
}
I printed "This is an example." in the file, "Example.dat" and I want to read it again from the file by code above but there's no string in the output. Why? Please help me.
You are opening the file in write-only mode ("w"). Use "w+" for reading and writing.
FILE *File_fp = fopen("Example.dat", "w+");
To read a file, you have to use the mode "r". Example:
FILE *File_fp = fopen("Example.dat", "r");
And you made a mistake in this code. If it fails to create a file, fopen() function will return NULL. Then the value of the file pointer would be NULL.
So, in your code if section will execute when the file is successfully created. So, change your code like this:
if(File_fp)
{
printf("An error occurred while creating the file.\n");
exit(1);
}
Just remove the (!) logical not sign.

canĀ“t open txt file

#include <stdio.h>
#include <stdlib.h>
int main()
{
char c[1000];
FILE *fptr;
if ((fptr = fopen("program.txt", "r")) == NULL)
{
printf("Error! opening file");
// Program exits if file pointer returns NULL.
exit(1);
}
// reads text until newline
fscanf(fptr,"%[^\n]", c);
printf("Data from the file:\n%s", c);
fclose(fptr);
return 0;
}
Output is Error! opening file
I have program and txt file in same dir.
How can I direct access to that file?
To diagnose, use the system command to issue a ls or dir depending on your platform. That will tell you where you are running from. Odds are it is a different location than the files you are trying to open.
As suggested in the comment, try replacing printf with perror
if ((fptr = fopen("program.txt", "r")) == NULL)
{
perror("Error");
// Program exits if file pointer returns NULL.
exit(1); // Exiting with a non-zero status.
}
perror prototype is
void perror(const char *str)
where str is the C string containing a custom message to be printed before the error message itself.
However some causes of the of the file not being read are
File is not present in the current working directory. If this is the case, rectifying the path should fix the issue.
The program might not have the permissions to read from the file usually because of a setting related to discretionary access control. Perhaps do a chmod with file?
I made a quick run of your program on TURBOC++ by Borland and it executed without complaining any sort of Warning or Error
As mentioned in the earlier posted answers, you should replace printf by perror
CURRENT REPLACE BY
printf("Error! opening file"); perror("Error! Opening File.");
As in your case of file not found printf("Error! opening file"); will result in :
Error! Opening file.
However in case of perror("Error! Opening File."); if the file program.txt does not exist, something similar to this may be expected as program output
The following error occurred: No such file or directory
The difference is obvious from above explanations.
Regarding your program, I am making an assumption that either your path to the file is wrong or there is some problem with your compiler.
Try to open your file in w+ mode also to ensure that the file exist.

Won't create txt file C program

This is my code
#include <stdio.h>
int main()
{
FILE *file;
file = fopen("file.txt","a+");
fprintf(file,"%s","test :)");
fclose(file);
return 0;
}
Don't understand why it won't create a txt file
help
Please try perror to check if you have permission to write to the file or not. That is the problem most of the time. Add this after fopen
if (!file)
perror("fopen");
You need to check for errors in your program. fopen() can fail for a variety of reasons. We can either inspect errno, or use perror / strerror to print a useful message.
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *file = fopen("file.txt","a+");
if (file == NULL) {
perror("Failed to open the file");
exit(-1);
}
fprintf(file,"%s","test :)");
fclose(file);
return 0;
}
For example, if a file exists in the current directory, but is owned by a different user:
[8:40am][wlynch#watermelon /tmp] ./foo
Failed to open the file: Permission denied
Create a file if one doesn't exist - C
here are answers...The one that's under the marked one worked for me on my s.o. The way you are trying to do doesn't work on windows, but works on linux. Sorry for saying what I said before...Both operating systems have their bright and not so bright side.

Basic file IO in C

I am working through the excellent The C Programming Language at the moment, and have got stuck while trying to open and read a file. The program compiles, but seg faults on execution:
$ ./a.out
Segmentation fault
Here is the code:
#include <stdio.h>
main()
{
FILE *fp;
fp=fopen("/home/c-sandbox/index.html", "r");
fprintf(fp, "Testing...\n");
fclose(fp);
}
Note that the path points to a real file containing the string "hello, world".
Any ideas on where I am going wrong?
Make sure fp is not NULL before trying to write to it. For example:
if(fp == NULL)
{
fprintf(stderr, "Cannot open file\n");
return EXIT_FAILURE; // defined in stdlib.h
}
You need to open the file with something other than "r", which only allows file reading. Read the man page for fopen to find out which mode would work the best for you. Example:
"w" - Truncate to zero length or create file for writing.
"a" - Append; open or create file for writing at end-of-file.
You opened the file for reading only, and are attempting to write to it.
Use "a" if you want to append to the end of the existing file.
Edit: As others have noted, you're also not checking to see if the file was opened. fopen will return NULL if it fails and set the global variable errno to a value that indicates why it failed. You can get a human-readable explanation using strerror(errno)
if( fp == NULL ) {
printf( "Error opening file: %s\n", strerror( errno ) );
}
You are opening it in readonly mode! Need to use w or a for writing/appending to the file :)
fopen("/home/c-sandbox/index.html", "w");
You should check that fopen does not return NULL. I suspect it is returning NULL and either the fprintf and/or fclose calls are getting messed up.
#include <stdio.h>
main()
{
FILE *fp;
fp=fopen("/home/c-sandbox/index.html", "r");
if(!fp)
{
perror ("The following error occurred");
return ;
}
fgets(line,len,fp);
printf("%s",line);
fclose(fp);
fp=fopen("/home/c-sandbox/index.html", "a");
if(!fp)
{
perror ("The following error occurred");
return ;
}
fprintf(fp, "Testing...\n");
fclose(fp)
}
for reading "hello, world" string present in file.
after reading write to the same file "Testing..."

why do I get errno EINVAL (innvalid parameters) but only when the file is empty

I use _fsopen(path, "r+", _SH_DENYRW) for opening a file in C any parameter for protection (_SH_...) cause the same issue.
When opening an empty file, errno is set to 22 (EINVAL), not so when the file isn't empty - then all is OK. What can I do?
The documentation implies that EINVAL would the result if one of the parameters were invalid. Since "r+" has to be a valid pointer, and assuming it compiled at all _SH_DENYRW has to be a valid flag, the only remaining question is whether your variable path is not NULL, points to memory that exists and can be read, and contains a valid path name.
I just tried the following:
#include <stdio.h>
#include <share.h>
int main(int argc, char **argv)
{
FILE *f;
if (argc != 2) {
fprintf(stderr, "Usage: %s file\n", argv[0]);
exit(1);
}
f = _fsopen(argv[1], "r+", _SH_DENYRW);
if (f) {
printf("Open ok.\n");
fclose(f);
} else {
perror(argv[1]);
}
return 0;
}
On files that exist and can be written, regardless of their size, it prints "Open ok.", meaning that _fsopen() succeeded. A couple of other cases:
A read-only file:
C:>fsopen ro.txt
ro.txt: Permission denied
No file:
C:>fsopen nosuchfile
nosuchfile: No such file or directory
A device file:
C:>fsopen NUL:
Open ok.
A zero-length file:
C:>fsopen zero.txt
Open ok.

Resources