Edit: Deleted all but the main question.
My program here is supposed to create a file at a specified directory, and write specified text to it. A correct file's path and content should look something like this:
Path: D:\test.txt
Content: The printing succeeded.
For some reason, my code won't recognize the "path" variable. I don't know what I'm doing wrong here. The "text" variable works fine.
#include<stdio.h>
int main()
{
//Declaring variables
char path[999];
char text[999];
FILE *fp;
//prompting for path variable
printf("Specify a file path.\n");
fgets(path,999,stdin);
printf(path);
//prompting for the text variable.
printf("What do you want to write?");
fgets(text,999,stdin);
printf(text);
//opening and printing to file.
//fp = fopen("D:\\test.txt", "w");
fp = fopen(path, "w");
fprintf(fp, text);
fclose(fp);
//test print to see that the program completed correctly.
printf("\nThe printing has been done.");
return 0;
}
The thing I don't understand is that fp = fopen("D:\\test.txt", "w"); works, but fp = fopen(path, "w"); doesn't. I've tried putting in these different paths.:
D:\\test.txt
D:\test.txt
D\test.txt
D\\test.txt
It doesn't open the file when you open the variable path because fgets() reads the newline and puts it at the end of the string (if there's enough space in the buffer). In order to make it work you have to manually remove the newline from the string.
Try this before opening the file.
if(isspace(path[strlen(path)-1]))
path[strlen(path)-1]='\0';
You might also need to include <ctype.h>
Related
How can I check if a text file has something written or not. I tried:
LOGIC checkfile(char * filename)
{
FILE *pf;
pf=fopen(filename,"wt");
fseek(pf,0,SEEK_END);
if(ftell(pf)==0)
printf("empty");
}
This function returns empty everytime, even in my text file I have few words or numbers written.
The problem is that you opened the file for writing. When you do that, everything in the file is lost, and the length of the file is truncated to 0.
So you need to open the file for reading. And the easiest way to see if the file is empty is to try to read the first character with fgetc. If fgetc returns EOF, then the file is empty.
First of all: DO NOT OPEN THE FILE FOR WRITING!
second: for knowing about file status in C you can use fstat which is in sys headear file!
You can use struct stat for using this function
here is a simple example:
#include <sys/stat.h>
int main(void)
{
int fields = 0;
int size = 0;
// Open the file test.txt through open()
// Note that since the call to open directly gives
// integer file descriptor so we used open here.
// One can also use fopen() that returns FILE*
// object. Use fileno() in that case to convert
// FILE* object into the integer file descriptor
if(fields = open(file_path, "r")){
struct stat buf;
fstat(fields, &buf);
size = (int)buf.st_size;
}
printf("size of file is %d", size);
return 0;
}
Note: I just include a header file that related to fstat. You can add other header files yourself
What about using fscanf to read the file, and check if something was actually read?
FILE *fp;
char buff[255] = "";
fp = fopen(filename, "r");
fscanf(fp, "%s", buff);
if (!*buff)
printf("Empty\n");
else
printf("%s\n", buff);
fclose(fp);
I've ran into a problem trying to open a file from user input. I can open it if the filename is correct the first time it's entered, but can't if it's correct in the while loop.
char file[256], *end;
printf("Enter the name of the file: ");
fgets(file, 256, stdin);
if((end=strchr(file, '\n'))!=NULL)
*end='\0';
FILE *fp=fopen(file, "r");
while(fp==NULL)
{
printf("The given file doesn't exist. Enter a file name: ");
fgets(file, 256, stdin);
if((end=strchr(file, '\n'))!=NULL)
*end='\0';
FILE *fp=fopen(file, "r");
}
I can open it if the filename is correct the first time it's entered, but can't if it's correct in the while loop.
No, you're being fooled. The problem is that the loop condition in while(fp==NULL) tests the value of variable fp declared outside the loop, and inside the loop you never set that variable, so if you enter the loop you will never exit.
But that doesn't mean you fail to open the file on the second attempt or a subsequent one. Inside the loop, you declare another variable fp, "shadowing" the one outside, and assign the result of fopen() to it. When this fopen() succeeds, you effectively ignore the result.
As another, now deleted, answer said, the main thing to do is to fix the loop so that it uses the same fp that is used outside. The smallest change that achieves that would yield this version of the loop:
while(fp==NULL)
{
printf("The given file doesn't exist. Enter a file name: ");
fgets(file, 256, stdin);
if((end=strchr(file, '\n'))!=NULL)
*end='\0';
fp=fopen(file, "r");
}
There are some other issues with the way you input the file name, both there and in the code preceding, as well as some unnecessary code duplication, but as long as the file names entered by the user are simple and short, that will do the trick.
You need to consider about the platform here, to make it your code cross platform file check the approach is different. If the platform is not important then you dont need to worry about Windows, in Linux you can use stat utility.
Simple way to check the existence of file(Checks in read-mode) :
int read_file_exists(const char *filename)
{
FILE *fp = fopen (filename, "r");
if (fp!=NULL) fclose (fp);
return (fp!=NULL);
}
Check this link for more information about C file check.
Right now, what I have is this:
#include <stdio.h>
#include <conio.h>
#include <string.h>
int main()
{
char fname[100];
FILE* fp;
memset(fname, 0, 100);
/* ask user for the name of the file */
printf("enter file name: ");
gets(fname);
fp = fopen(fname, "w");
/* Checks if the file us unable to be opened, then it shows the
error message */
if (fp == NULL)
printf("\nError, Unable to open the file for reading\n");
else
printf("hello");
getch();
}
This functions just fine, but is there a way I can force it to save as a .txt or a .data or something? Right now it just saves as the name you put in with no extension. Other than asking the user to just input the name and extension, I can't think of a way to do that. I mean, it still works just fine for reading/writing purposes, I just think an extension would be nice.
to expand my comment:
strcat(fname, ".txt");
The strcat function can be used to append text to a destination buffer, assuming the destination is large enough to store the new text.
char *strcat(char *destination, const char *source);
The source is the new text that you want to append (in your case the extension), and the destination is where the new text will be added. If destination is not big enough, then the behavior is undefined.
One could also use the snprintf function to append text, which is safer, as it takes a size argument.
I figured it out. Credit goes to a friend of mine who showed this to me earlier today.
int main()
{
FILE *Fileptr;
char filename[50];
char file[50];
int c;
printf("What do you want to name your file?");
scanf("%s", filename);
sprintf(file, "%s.txt", filename);
Fileptr = fopen(file, "w");
fprintf(Fileptr, "Data goes here");
fclose(Fileptr);
return 0;
}
Much easier than what I had been doing.
I want to open a file. Easy enough. Use fopen(). However, what file to open depends on the user input. I am somewhat proficient in Korn Shell scripting and this is easily done using variable substitution: $(var). I am unable to figure out the correct format in C. Could someone please give me some insight?
My code -
#include <stdlib.h>
#include <stdio.h>
char statsA[100];
char fileA[50];
int main (void)
{
printf("Enter file to open\n");
gets(fileA);
FILE *statsA;
statsA = fopen("c:/Users/SeanA/C/***<fileA>***", "r+");
.......................................^ What goes here?
I am unsure of how to include the user input in the fopen string.
This is what sprintf is for. It works like printf, except that its output goes to a string instead of stdout.
char filename[100];
sprintf(filename, "c:/Users/SeanA/C/%s", fileA);
statsA = fopen(filename, "r+");
Also, the definition of statsA you have inside of main masks the definition at file scope. You probably want to give these different names.
You must concatenate both strings manually. Something like this
char* folder = "c:/Users/SeanA/C/";
char* path = malloc(strlen(fileA) + strlen(folder) + 1);
path = strcpy(folder);
path = strcat(fileA);
FILE *statsA = fopen(path, "r+");
free(path);//Always free your memory
Do scanf to get the file from the user.
make a char array to hold the filename.
char filename[15];
Now ask for the file name:
printf("What is the name of the file?\n");
scanf("%s", &filename);
Note: Include the FULL file name. so if I have a text doc called filename The user would need to type filename.txt
Now you have the file name you can declare a file pointer
FILE * fp;
fp = fopen(filename, "r");
Now you should be able to scan your file!
fscanf(fp, "%d", &value);
EDIT: I did not notice you wanted string concatenation with your file path.
Since you know the predefined path you can make another char array that holds that string path
char fullPath[100];
char path[75] = "c:/Users/SeanA/C/";
Now you can use strcat to bring them all together!
strcat(fullPath, path);
strcat(fullPath, filename);
Now you do fopen(fullPath, "r");
i was trying this problem from usaco. when i use txt file while using file the program is working fine. but when for the submission requirement i change the format to beads.in and beads.out the program crashes. what;s the problem?
here's my code:
#include <stdio.h>
#include<string.h>
main () {
FILE *fin = fopen ("beads.in", "r");
FILE *fout = fopen ("beads.out", "w");
int n;
char str[400];
char now,rev_now;
int pos,forward,reverse,sum,max=0,i,j,k;
fscanf(fin,"%d\n%s",&n,str);
n--;
for(pos=0;pos<=n;pos++){
now=str[pos];
if(pos==0)k=n;
else k=pos-1;
rev_now=str[k];
forward=2;
int flag1=0,flag2=0,reverse=2;
for(i=pos,j=k;;){
if(i==n)i=-1;
if((str[i+1]==now||str[i+1]=='w')&&flag1==0){
i++;
forward++;
}
else{
flag1=1;
}
if(j==0)j=n+1;
if((str[j-1]==rev_now||str[j-1]=='w')&&flag2==0){
j++;
reverse++;
}
else{
flag2=1;
}
if(flag1==1 && flag2==1)break;
}
sum=forward+reverse;
if(max<sum){max=sum;}
}
fprintf(fout,"%d\n",max);
return 0;
}
are you sure beads.in and beads.out are created already..
According to man page
r Open text file for reading. The stream is positioned at the
beginning of the file.
w Truncate file to zero length or create text file for writing.
The stream is positioned at the beginning of the file.
May be beads.in is not created in prior to fopen. It's better if you check the status of the fopen, use perror.
You mention that it works with a text file. I'm guessing that beads.in is not a text file, but rather a binary file. If that is the case, then #KVD's suggestion above to use: fopen ("beads.in", "rb"); and fopen ("beads.out", "wb"); should work. The reason the program would crash with binary input data is because you are asking fscanf to copy data into your str buffer until it encounters a newline character. More than likely, the beads.in file has more than 400 characters which will cause a buffer overflow and start overwriting the program stack.