I'm trying to check a directory for a file. I've done that properly. But I'm having trouble for exceptions--> when the file is not there. Here's what I am wanting to do: I 'd like to check for the file, if it exists, then exit the loop. If the file does not exist, then sleep. After sleeping for 3 seconds, check for the file again. Repeat until the file is found then return to main() and print "Hello everyone".
Currently, if the file is missing and i put the file into this directory while the program is running, it never recognizes the new file until i stop the program then start it back up. I want the program to check for the file again after sleep.
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <curl/curl.h>
#include <unistd.h>
#define MYFILE "/Users/stackoverflow/Documents/fileabc123"
int checkfile() {
FILE *pFile;
pFile = fopen(MYFILE,"r");
char file_string[40];
int repeat = 0;
while( repeat < 1) {
if (pFile!=NULL) {
fgets (file_string,36,pFile);
fclose (pFile);
printf("%s\n", file_string);
repeat = 1 ;
}
if (pFile ==NULL) {
printf("Machine cannot read system file. \n");
sleep(3);
}
}
}
int main (int argc, char ** argv) {
checkfile();
printf("Hello everyone\n");
return 0;
}
You need to put the fopen in the loop.
if ((pFile = fopen(MYFILE, "r")) != NULL) {
// read it
}
else {
printf("Failed opening");
}
The error is in the loop.
you simply aren't trying to open the file again :)
this give you 2 error:
1. if you put the file it is not seen, as the program does not try to open it
2. if the file is present, you read it, then you close it, leaving an INVALID file descriptr but that is NOT null
this mean next loop you will try to read an invalid file descriptor. It is like reading/writing value with a overflow index from an array, or from a free() pointer.
You will almost always have the right value.. until that ram is reallocated.
so:
1. you have to try to open a file, until you get a valid file descriptor.
2. close will not change pointer value. It simply can't, think about it.
if you whant to change the value of somthing, you have to give it's address. A pointer is the adress of somthing. So File* is pointing to a File, but if you want to change the address pointed by File*, you need it's address (&pFile), just like a scanf :)
Related
It's my first exercise about Files and I have to write some code so that if I write a word in the console, it gets printed in the file. The program ends if I input the word "fine" (it's Italian for end). It seems like the file is opened and closed correctly, the program reads the inserted chars, but nonetheless, the file remains blank.
I tried opening the file in various modes, I tried printing how many chars were read, I even tried deleting the file (but it actually does't exit even if I added exit(1).
#define _CRT_SECURE_NO_DEPRECATE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
int main() {
FILE * fp;
char s[64];
if ((fp = fopen("prova.txt", "r+")) == NULL) {
printf("Error.\n");
exit(1);
}
do {
scanf("%s", s);
if (strcmp("fine", s) != 0) {
fprintf(fp, "%s ", s);
}
} while (strcmp("fine", s) != 0);
fclose (fp);
return 0;
}
It should save all the words in a text file, but it remains blank.
Your program looks OK. Most likely, you are checking the wrong file.
An educated guess: you are using some IDE. If this is the case, the file is created, but is created somewhere else. To be sure, print the working directory (man getcwd) somewhere in the beginning of your program, and look for the file there.
you have to use "w" to open a new file with write priviledges
change
if ((fp = fopen("prova.txt", "r+")) == NULL) {
with
if ((fp = fopen("prova.txt", "w+")) == NULL) {
EDIT: Maybe i didn't explained myself, r+ will fail if the file doesn't exist, changing it works for me
I'm new to C and I'm trying to open a file and print its content line by line to console.
The source code is attached along with a couple screen shots to show my situation. (The redded-out part contain my computer's directories and personal info). As you can see from the screenshot, the program prints "before" but not "after". Of course, neither does it print out anything from coc.txt.
I can't figure out why this is the case. Everything seems correct and I don't see any errors.
#include <stdio.h>
#include <stdlib.h> // For exit()
const int MAX_LINE_LENGTH = 300;
int main() {
FILE *inputFile;
inputFile = fopen("coc.txt", "r");
char lineRead[MAX_LINE_LENGTH];
printf("before\n");
while(!feof(inputFile)) {
fgets(lineRead, MAX_LINE_LENGTH, inputFile);
puts(lineRead);
}
fclose(inputFile);
printf("after\n");
}
console
coc.txt
Here's a suggested alternative (not tested yet):
#include <stdio.h>
#define MAX_LINE_LENGTH 300
#define NULL 0
int main(int argc, char *argv[]) {
FILE *inputFile;
char fname[MAX_LINE_LENGTH], lineRead[MAX_LINE_LENGTH];
/* Get filename from cmd-line */
if (argc != 2) {
printf ("USAGE: progname <fname>\n");
return 1;
}
/* Try to open file */
if ((inputFile = fopen("coc.txt", "r")) == NULL) {
perror("Could not open file");
return 2;
}
/* Now read the file, and echo back a line at a time */
printf("before...\n");
while(fgets(lineRead, MAX_LINE_LENGTH, inputFile) != NULL) {
printf ("%s", lineRead);
}
printf("\n...after\n");
/* Cleanup and exit */
fclose(inputFile);
return 0;
}
Changes:
Be sure to have a "return" from main ().
In general, a graceful "return" from main() is preferred over a system call to "exit()".
Read the input, then to check for EOF (fgets() == NULL).
Make sure you've opened the file before reading.
Rather than hard-coding the filename, we're reading it from the command line.
Rather than puts() (which always appends a newline, regardless of whether the string already has a newline), we're using printf().
Make sure that the coc.txt file and the read.c files are in the same folder. I executed your original code and it works fine with VS 2017 on windows 10.
I'm importing a txtfile into my file, how do i check if the input file is blank.
I already check if it cannot read the input. This is what i have so far:
#include<stdio.h>
#include<stdlib.h>
int main (int argc, char *argv[]){
// argv[1] will contain the file name input.
FILE *file = fopen(argv[1], "r");
// need to make sure the file is not empty, error case.
if (file == NULL){
printf("error");
exit(0);
}
// if the file is empty, print an empty line.
int size = ftell(file); // see if file is empty (size 0)
if (size == 0){
printf("\n");
}
printf("%d",size);
the size checking obviously does not work because i put in a few numbers and the size is still 0. any suggestions?
If you are working with a regular file (e.g., a text file), you can use sys/stat.h and call the value of the st_size struct member:
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
int main (int argc, char *argv[]) {
if (argc != 2) {
return EXIT_FAILURE;
}
const char *filename = argv[1];
struct stat st;
if (stat(filename, &st) != 0) {
return EXIT_FAILURE;
}
fprintf(stdout, "file size: %zd\n", st.st_size);
return EXIT_SUCCESS;
}
how about try read first row.
and see what characters you get?
Call ftell() does not tell you the size of the file. From the man page:
The ftell() function obtains the current value
of the file position indicator for the stream
pointed to by stream.
That is, it tell you your current position in the file...which will always be 0 for a newly opened file. You need to seek to the end of the file first (see fseek()).
ftell will tell you the position the file pointer is at, and immediately after you opened the file, this position is always 0.
You either use stat before opening, or use fseek to seek some distance in the file (or at end) and then use ftell.
Or you delay the check until afterwards. I.e., you try to read whatever you need to read, and then verify whether you succeeded or not.
Update: and speaking of checks, you have no guarantee that
// argv[1] will contain the file name input.
For that, you need to check out that argc is at least 2 (the first argument being the executable name). Otherwise your file name might be NULL. fopen should simply return NULL, but in other scenarios you might find yourself looking at a core dump.
I'm trying to create 5000 junk files, write them to a file and delete them. But this code only is writing a portion of the files to the file. ls -l | grep ^- | wc -l says I have 1598 files remaining in the directory that is supposed to be emptied with unlink();. If I remove close(fd) I get a seg fault if I do any more than 1000 files. Any suggestions?
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <sys/types.h>
#include <dirent.h>
#include <errno.h>
main (int argv, char *args[]){
if(argv<3){
printf("Please run with proper command line arguements.\n");
return;
}
int numFiles = atoi(args[1]);
char *fileName = args[2];
char *fileList[numFiles];
int x, ret,fd;
char buff[50];
for(x=0;x<numFiles;x++){
ret = sprintf(buff,"./stuff/%s-%d.junk",fileName, x);
fd = creat(buff);
close(fd);
}
DIR *odir = opendir("./stuff");
struct dirent *rdir = NULL;
FILE *fp;
fp = fopen("./files.list", "w");
x=0;
while(rdir = readdir(odir)){
char* name = rdir->d_name;
ret = sprintf(buff,"./stuff/%s-%d.junk",fileName, x);
if(strcmp(name,"..")!=0){
if(strcmp(name,".")!=0){
fprintf(fp,"%s %d\n",name,x);
x++;
}
}
unlink(buff);
}
close(fp);
closedir(odir);
}
Thanks!
Note: Use of creat(), opendir(), readdir() and unlink() were required for the assignment. And as for error checking, your right of course but I'm under time constraints and the TA really, really doesn't care... But thank you all!
Here you're using fopen:
FILE *fp;
fp = fopen("./files.list", "w");
But then you're using close instead of fclose to close it:
close(fp);
I'm not at all sure this is what's causing the problem you're seeing, but it's definitely wrong anyway. You probably just want unlink(rdir->d_name) instead of unlink(buff). You embedded the number into the file name when you created it -- you don't need to do it again when you're reading in the name of the file you created.
You're removing things from the directory while calling readdir; I think that's supposed to work OK, but you might want to consider avoiding it.
More to the point: as you iterate over the directory with readdir you're potentially removing different files from the ones readdir is listing. (Because what you pass to unlink is buff which you've filled in from the steadily-incrementing x rather than from anything returned by readdir.) So, here's a toy example to show why that's problematic. Suppose the directory contains files 1,2,3,4 and readdir lists them in the order 4,3,2,1.
readdir tells you about file 4. You delete file 1.
readdir tells you about file 3. You delete file 2.
readdir would have told you about file 2, but it's gone so it doesn't.
readdir would have told you about file 1, but it's gone so it doesn't.
You end up with files 3 and 4 still in the directory.
I'm trying to make a program to open a file, called "write.txt".
#include <stdio.h>
main() {
FILE *fp;
fp = fopen("write.txt", "w");
return 0;
}
Should this work? Because it returns nothing.
Other than an old variant of main, there's not really much wrong with that code. It should, barring errors, create the file.
However, since you're not checking the return value from fopen, you may get an error of some sort and not know about it.
I'd start with:
#include <stdio.h>
#include <errno.h>
int main (void) {
FILE *fp;
fp = fopen ("write.txt","w");
if (fp == NULL) {
printf ("File not created okay, errno = %d\n", errno);
return 1;
}
//fprintf (fp, "Hello, there.\n"); // if you want something in the file.
fclose (fp);
printf ("File created okay\n");
return 0;
}
If you're adamant that the file isn't being created but the above code says it is, then you may be a victim of the dreaded "IDE is working in a different directory from what you think" syndrome :-)
Some IDEs (such as Visual Studio) will actually run your code while they're in a directory like <solution-name>\bin or <solution-name>\debug. You can find out by putting:
system ("cd"); // for Windows
system ("pwd") // for UNIXy systems
in to your code to see where it's running. That's where a file will be created if you specify a relative path line "write.txt". Otherwise, you can specify an absolute path to ensure it tries to create it at a specific point in the file system.
What did you expect it to 'return' - it opens a file, on most platforms creating one if it doesn't exist.
You should probably fclose(fp) the file at the end.
I think you want to print the contents of file write.txt. (Assume it contains characters).
#include <stdio.h>
int main()
{
FILE *fp,char ch;
fp=fopen("write.txt","r");
if(fp==NULL)
{
printf("Some problem in opening the file");
exit(0);
}
else
{
while((ch=fgetc(fp))!=EOF)
{
printf("%c",ch);
}
}
fclose(fp);
return 0;
}
I think you should study some more fundamentals in C before you start attempting to work with files. A return means some data is passed back to the calling code from the called function.In this case you return 0 at the end of your program. You did not do anything with your FILE pointer except cause a new file to be created...