I am trying to run a simple test to read and print a file to console. I have my "main.c" file and "myfile.txt" in the same folder on my desktop (Mac). However, when running the program I receive "No such file or directory." I tried changing the address to everything I can think of... Can someone please point out what I am doing wrong? My apologies I am new to this and have hit a wall.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
FILE * file;
char str [256];
file = fopen("myfile.txt", "r");
if (NULL == file)
{
perror("Error when opening file!");
return -1;
}
if(fgets(str, 10, file) != NULL)
{
printf("%s", &str);
}
fclose(file);
}
I was expecting to print the first 10 chars of the txt file into the console. Instead I received "No such file or directory."
Related
I want to write a program in C which just reads a file, stores it into an array and then prints the array. Everything works fine but when the text file has more than one line, I always just get the last line printed out.
This is my Code:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char * argv[]) {
FILE * stream;
char dateiname[255];
stream = fopen("heute.txt", "r");
if(stream == NULL){
printf("Error");
}else {
while(!feof(stream)){
fgets(dateiname, 255, stream);
}
fclose(stream);
}
printf("%s\n", dateiname);
}
Thanks for help!
Everything works fine but when the text file has more than one line, I always just get the last line printed out
Reason: For every iteration, the data gets replaced with the next line data, and at the end dateiname will read only the last line.
while(!feof(stream))
Usage of feof() is not recommended. Please see this link for more information :https://faq.cprogramming.com/cgi-bin/smartfaq.cgi?id=1043284351&answer=1046476070
Please see the following code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *stream;
char dateiname[1024];
int i = 0;
stream = fopen("heute.txt", "r");
if (stream == NULL)
{
printf("Error");
}
else
{
while (fgets(dateiname, sizeof(dateiname), stream) != NULL)
{
printf("Line %4d: %s", i, dateiname);
i++;
}
}
return 0;
}
If you want to just read and print the contents of the file you no need to worry about the size of the file and how many number of lines you have in file.
you can just run fgets() in the while and print each line until we reach NULL
But if you want to store them, we need to calculate the size of the file.
So we need to use functions like stat or fstat to get the size of the file and allocate memory dynamically then just read that many bytes.
I want to write a code to extract todo task list from a code file.It's basically scanning a code file and detecting lines that include "TODO" string and then writing those lines into a text file.
So far my my code is like this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
FILE* f;
char line[200];
f = fopen("someFile.c", "r");
char c;
char str;
while(!feof(f)){
fgets(line,sizeof(line),f);
if(strstr(line, "TODO") != NULL)//Extracts every line with TODO
{
c=fgetc(f);//c = lines with TODO
}
}
fclose(f);
f= fopen("todoListFile.txt","w");
while(!feof(f))
{
fputs(c,f);//Writing the content of the c in to the text file.
}
fclose(f);
return 0;
}
When I run this code it crashes after 1-2 seconds.
My mistake is probably at the second part which is getting those "TODO" lines and writing down those to the text lines. But I'm pretty stuck at that part and don't know what to do.
Note: Content of someFile.c is basically some comment lines with "// TODO :"
The specification pretty much indicates that you have to open two files, one for reading, one for writing. As you read a line from the input file, if that line contains TODO, you need to write that line to the output file. That leads to the straight-forward code:
#include <stdio.h>
#include <string.h>
int main(void)
{
char file1[] = "someFile.c";
char file2[] = "todoListFile.txt";
FILE *fp1 = fopen(file1, "r");
if (fp1 == NULL)
{
fprintf(stderr, "Failed to open file %s for reading\n", file1);
return 1;
}
FILE *fp2 = fopen(file2, "w");
if (fp2 == NULL)
{
fprintf(stderr, "Failed to open file %s for writing\n", file2);
return 1;
}
char line[200];
while (fgets(line, sizeof(line), fp1) != 0)
{
if (strstr(line, "TODO") != NULL)
fputs(line, fp2);
}
fclose(fp1);
fclose(fp2);
return 0;
}
Note that it checks that the files were opened successfully, and reports the file name if it failed, and exits with a non-zero status (you could add <stdlib.h> and use EXIT_FAILURE if you prefer).
When run on (a copy of) its own source, it leaves the todoListFile.txt containing one line:
if (strstr(line, "TODO") != NULL)
Simple modifications of the program would:
Write to standard output instead a fixed name file.
Take command line arguments and process all the input files named.
Read standard input if no input files are named.
Increase the line length. 200 is better than 80, but lines can be longer than that. I tend to use 4096 as a line length unless there's a reason to allow longer lines.
I'm currently working on an old coding problem from USACO in C. Here are the first couple lines of my code, in which I am trying to use the fscanf() function to grab the first value, an int, from the blocks.in file:
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *fin = fopen ("blocks.in", "r");
FILE *fout = fopen ("blocks.out", "w");
int i,j;
int linecount = 0;
int alphabetCount[26];
fscanf(fin," %d",&linecount);
Running gdb (as a part of the Eclipse C/C++ IDE), I consistently get a segmentation fault error on the line:
fscanf(fin," %d",&linecount);
The error consistently reads:
No source available for "flockfile() at 0x7fff855e6d39"
I haven't been able to source the issue. I've not had any problems with this in the past. Do you see what is wrong, or have a better solution/function with which to extract the data?
I suspect that there is no blocks.in file in the directory from which you run the program. Even if the file is present, it may not open successfully. Some simple error-checking could help you avoid problems here:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
FILE *fin;
FILE *fout;
int i,j;
int linecount = 0;
int alphabetCount[26];
if ((fin = fopen("blocks.in", "r")) == NULL) {
fprintf(stderr, "Unable to open input file\n");
exit(EXIT_FAILURE);
}
if ((fout = fopen("blocks.out", "w")) == NULL) {
fprintf(stderr, "Unable to open output file\n");
exit(EXIT_FAILURE);
}
fscanf(fin," %d",&linecount);
return 0;
}
While im studying C from a old book (that might be the problem), i wrote the code to copy the content of one file to another one.
But somehow, the program stops working. I would appreciate some help.
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char *argv[])
{
FILE *fin, *fout; //Pointers to the files
int ch;
if (argc!=3) //Just checking if the user inserted the correct information
{
printf("\nCorrect mode: Program name, file1 -> file2 \n\n");
exit(1);
}
fin=fopen(argv[1], "rb");
if (fin==NULL) //Checking if the file exists
{
printf("\n\nERROR!\n\nThe file you're trying to open does not exist or it cannot be opened.\n\n");
exit(2);
}
if ((fout=fopen(argv[2], "wb"))==NULL) // If it cannot create a file
{
printf("\n\nERROR!\n\nImpossible to create the file %s\n\n", argv[2]);
exit(3);
}
while ((ch=fgetc(fin))!=EOF)
fputs(ch, fout);
fclose(fin);
fclose(fout);
}
You are using fputs to write the characters. It is used for strings (arrays of char). Instead use fputc.
Hello all I'm trying to read a large txt file, word by word, then print each word out then continue on with the loop until EOF but I got no output after running this code. I check everything, file name was correct, the file also in the same folder with my c file. Could anyone please explain what is going on? Thank you. Here is the txt file, and the code:
.txt file
#include <stdio.h>
#include <string.h>
int main(void) {
FILE *infile;
char temp_1[25];
setvbuf(stdout, NULL, _IONBF, 0);
infile = fopen("LittleRegiment.txt", "r");
if(infile != NULL) {
while(fscanf(infile, "%s", temp_1) != EOF) {
printf("%s ", temp_1);
}
} else {
printf("Couldn't open the file.");
}
return 0;
}
Try printing the reason for the error.
} else {
//printf("Couldn't open the file.");
perror("open file"); // prototype in <stdio.h>
}