Just testing out file descriptors. My aim is to open up a file stream with fopen and using fprintf write the file descriptors integer value back into the file to see what results im getting.
(I decided using fopen, fprintf etc) as it allowed me to write in variables, write() wouldn't allow it,
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
int main ()
{
FILE *fp;
fp = fopen("wow.txt", "w+");
if (fp < 0)
{
printf("ERROR \n");
}
else
{
printf("we good \n");
}
fprintf(fp, "hi %p \n", fp);
}
Issue i am facing is, if i write %d for the fprintf statement...i get a compiler error. If i write %p, I get the address in RAM.
Is it possible to get the absolute integer value...like "3"
FILE *fp;
is not a file descriptor, it's a file stream pointer and, as such, you need to treat it as a pointer.
A file descriptor is a small integer returned from one of the UNIXy calls like open or creat, while file pointers are sort of a level above that, assuming you're in an environment that even has descriptors.
In those environments, you can generally get at the underlying descriptor with something like:
int fd = fileno (fp);
The following complete program (under CygWin) shows this in action:
#include <stdio.h>
int main (void) {
FILE *fp = fopen ("wow.txt", "w+");
if (fp < 0) {
printf ("ERROR\n");
return 1;
}
fprintf (fp, "fp=%p, fd=%d\n", fp, fileno (fp));
fclose (fp);
return 0;
}
Compiling that with:
gcc -o testprog testprog.c
gives the output:
fp=0x800102a8, fd=3
Related
I've run the following code in Borland C and got following error:
Thread stopped. j:\bc5\bin\file\pro001.exe:fault access violation at
0x4043cc : read of address 0x12.
#include <stdio.h>
#include <stdlib.h>
main()
{
FILE *fp;
fp=fopen ("C:\Users\MEYSAM\Desktop\1.txt","w+");
fprintf (fp,"This is testing for fprintf ...\n");
fputs ("that is output filename by reference.",m);
fclose (fp);
}
Probably the fopen() failed, returning a NULL file pointer.
You must always check that I/O operations succeed.
You need this:
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp;
fp=fopen ("C:\\Users\\MEYSAM\\Desktop\\1.txt","w+");
// ^ using \\ instead of \, you need to escape the \ character
if (fp == NULL) // << checking if file could not be opened
{
printf("Could not open file.\n");
return 1;
}
fprintf (fp,"This is testing for fprintf ...\n");
fputs ("that is output filename by reference.", fp);
// ^ replaced m by fp
fclose (fp);
}
First of all you did not check if the fopen has been succeeded. Another problem is that in your code you wrote:
fputs ("that is output filename by reference.",m);
in which m is undefined and should be the name of the file, so it should be fp.
Here you can find the usage of fputs.
#include <stdio.h>
#include <stdlib.h>
#define FILE_NAME "ff.txt"
int main() {
char x[10],y[10];
FILE *fp;
fp = fopen(FILE_NAME, "r+");
if (fp == NULL) {
printf("couldn't find %s\n ",FILE_NAME);
exit(EXIT_FAILURE);
}
fprintf(fp,"Hello2 World\n");
fflush(fp);
fscanf(fp,"%s %s",x,y);
printf("%s %s",x,y);
fclose(fp);
return 0;
}
Here's a boiled down version of what I am trying to do. This code doesn't print anything in the console. If I remove the fprintf call, it prints the first 2 strings in the file, for me its Hello2 World. Why is this happening? Even after I fflush the fp?
After fprintf(), the file pointer points to the end of the file. You can use fseek() to set the filepointer at the start of the file:
fprintf(fp,"Hello2 World\n");
fflush(fp);
fseek(fp, 0, SEEK_SET);
fscanf(fp,"%s %s",x,y);
Or even better as suggested by #Peter, use rewind():
rewind(fp);
rewind:
The end-of-file and error internal indicators associated to the stream
are cleared after a successful call to this function, and all effects
from previous calls to ungetc on this stream are dropped.
On streams open for update (read+write), a call to rewind allows to
switch between reading and writing.
It is always best to check the return code of fscanf() too.
To avoid buffer overflow, you can use:
fscanf(fp,"%9s %9s",x,y);
Well, I try to play a bit with stack overflow and security cookies,
But its seem that most of the tutorial programs that people with POC tutorial with them are not compile with security cookies.
So i decide to create a program that take input from file and create a buffer overflow.
This is what I come out with:
#include <stdio.h>
#include <string.h>
void manipulate(char *buffer)
{
char newbuffer[80];
strcpy(newbuffer, buffer);
}
int main()
{
char ch, buffer[4096];
char filename[] = "exploit.txt";
int i = 0;
FILE *inFile;
inFile = fopen(filename, "rb");
if (inFile == NULL)
{
fprintf(stderr, "Can't open input file !\n");
getchar();
return 1 ;
}
while (buffer[i] != EOF)
{
buffer[i++] = fgetc(inFile);
manipulate(buffer);
printf("The value of i is : %d\n", i);
getchar();
return 0;
}
}
My problem is that I am always get Can't open input file !\n. even when i created "exploit.txt" in the same location and put some "aaaa" in it.
The basics of opening a file are correct. You can improve your program by using errno and strerror to inform the user of why the attempt to open the file failed.
#include <errno.h>
fprintf(stderr, "Error opening \"%s\": %s\n", filename, strerror(errno));
I was able to successfully run your example program (ignoring the stack overflow portion) with no changes.
The issue is with the value of the current or present working directory which is used as the basis for the completing file path used to open any file.
You can check the program's working directory using either getcwd() from <unixstd.h> for Linux, BSD, and POSIX systems or _getcwd() from <direct.h> for some other type.
Nitpicking: The "txt" file extension is misleading when compared with the fopen opening in binary mode, as specificed by rb.
I'm having a bit of a problem with a lab I'm working on for school.
What it's supposed to do is check to see if a file exists or not. My code works fine except one line, when I try to check to see if the file exists or not. Even if the file exists, it's returning as if it's not there always. Yet if I hard code the file name into the program it works fine. I'm just trying to figure out what's causing the file name to be interpreted wrong when I pass it into accept (or fopen I've tried both).
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main() {
//open lab4.in
FILE *file = fopen("lab4.in", "r");
if (file == 0) {
printf("Unable to open lab4.in for reading");
exit(-1);
}
//get the file name to check
char filetocheck[120], output[12];
fgets(filetocheck, 120, file);
int i;
//open lab4.out for writing
unlink("lab4.out");
FILE *write = fopen("lab4.out", "w");
fgets(output, 12, file);
//check the file is there and write the characters to lab4.out
if (access(filetocheck, F_OK) == -1){
for (i=5; i<10; i++){
fputc(output[i], write);
}
} else {
for (i=0; i<5; i++){
fputc(output[i], write);
}
}
//close the files at the end
fclose(write);
fclose(file);
}
Okay, when an I/O operation like this fails, as well as the -1, you get a result in a global int errno;
Where you have your printf, replace that with
perror(argv[0]); /* or something else useful. See below */
and add the declaration
int errno;
between your #includes and the int main, and you'll get a useful error message.
(PS: Two things to check: make sure the file's where you expect it, and use ls -l to make sure it's readable.)
Update
Dammit, that's what I get for not checking the man page. The argument to perror is indeed a string, used to preface the error message.
In this statement:
fgets(filetocheck, 120, file);
you may be getting an unwanted carriage return as part of your filetocheck buffer.
I would like to know how the contents of a file can be cleared in C. I know it can be done using truncate, but I can't find any source clearly describing how.
The other answers explain how to use truncate correctly... but if you found yourself on a non-POSIX system that doesn't have unistd.h, then the easiest thing to do is just open the file for writing and immediately close it:
#include <stdio.h>
int main()
{
FILE *file = fopen("asdf.txt", "w");
if (!file)
{
perror("Could not open file");
}
fclose(file);
return 0;
}
Opening a file with "w" (for write mode) "empties" the file so you can start overwriting it; immediately closing it then results in a 0-length file.
The truncate() call in UNIX is simply:
truncate("/some/path/file", 0);
While you can just open and close the file, the truncate call is designed specifically for this use case:
#include <unistd.h> //for truncate
#include <stdio.h> //for perror
int main()
{
if (truncate("/home/fmark/file.txt", 0) == -1){
perror("Could not truncate")
}
return 0;
}
If you already have the file open, you can use that handle with ftruncate:
#include <stdio.h> //for fopen, perror
#include <unistd.h> //for ftruncate
int main()
{
FILE *file = fopen("asdf.txt", "r+");
if (file == NULL) {
perror("could not open file");
}
//do something with the contents of file
if (ftruncate(file, 0) == -1){
perror("Could not truncate")
}
fclose(file);
return 0;
}
truncate(2) is not a portable call. It only conforms to 4.2BSD. While it is found on most *nix type systems, I would say use a POSIX.1 compliant routines which are pretty much guaranteed on most modern environments (including Windows).
so here is a POSIX.1-2000 compliant code snippet:
int truncate_file(const char *name) {
int fd;
fd = open (name, O_TRUNC|O_WRONLY);
if ( fd >= 0 )
close(fd); /* open can return 0 as a valid descriptor */
return fd;
}
For deleting the contents of a fie obviously there is basic method of opening a file in write mode "w" and then close it without doing any changes in it.
FILE *fp = fopen (file_path, "w");
fclose(fp);
this will delete all the data in file as when you open a already existing file using "w" mode the file is deleted and a new file with the same name is opened for writing, this will result into deletion of contents of your file.
BUT there is truncate syscall in UNIX systems, which is specially for the same purpose and pretty easy to use:
truncate (filepath, 0);
if you have already opened your file so either you close your file before doing truncate or use ftruncate
ftruncate (file_path, 0);