Full Edit:
I am getting frustrated, I don't know what am I doing wrong in here
I still have so many stuff to do in the code but I can't even open a file to continue my work.
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
void main()
{
char letter;
FILE *fp;
fp=fopen("C:\\Users\\LENOVO\\Desktop\\data.txt","r");
if(fp==NULL)
{
printf("error");
getch();
exit(1);
}
while(fscanf(fp,"%d",&letter)!=EOF)
putchar(letter);
getch();
fclose(fp);
}
Picture of the path: http://imgur.com/a/YwFYy
Still prints error
Ok, firstly let's take a look at your file path. There are two ways to acces a file from your local storage:
relative addresses if the file has the same root folder as your application
absolute addresses if the file is in a determined place on your machine's storage
I see that you are trying to use an absolute address to read from your file. Your path is correct but you have to take care about string formatting in C because the \ character could be interpreted as something else.
I would suggest to use this instead ( double back-slash )
input=fopen("C:\\Users\\LENOVO\\Desktop\\data.txt","r");
This will prevent string formatting interpretations.
Secondly, EOF is just a predefined macro constant and i think it is equal to -1 so your while(! (-1) ) code is not a good ideea for reading until the end of the file.
In order to read from a file until you reach the its end i would consider this property of fscanf() :
fscanf() returns EOF when it reaches the end of the file.
while(fscanf(input,"%ch",&letter) != EOF) {
putchar(letter);
}
This way of reading from a file should do the job.
To read everything from a text file and store its contents into a buffer:
First, you should count how many characters there are in the text file:
size_t get_file_len(FILE *fp)
{
size_t num = 0;
while (fgetc(fp) != EOF)
num++;
return (fseek(fp, 0, SEEK_SET) == 0 ? num : 0);
}
Then allocate memory for a buffer large enough and read all the characters:
char *load_text(const char *path)
{
char *buf = NULL;
FILE *fp = NULL;
size_t num = 0;
size_t i = 0;
int c = 0;
/* open the file in text mode */
fp = fopen(path, "r");
if (!fp)
return NULL;
/* if the file was empty or if an error occurred, return error */
if ((num = get_file_len(fp)) == 0) {
fclose(fp);
return NULL;
}
buf = malloc(num + 1);
if (!buf) {
fclose(fp);
return NULL;
}
while ((c = fgetc(fp)) != EOF)
buf[i++] = (char)c;
/* ensure that the string is null-terminated */
buf[i] = '\0';
fclose(fp);
return buf;
}
Also, in C, all escape sequences begin with a '\' (backslash), so if you wanted to write a backslash in a string or a char you should write it as a '\\' (double backslash):
input=fopen("C:\\Users\\LENOVO\\Desktop\\data.txt","r");
pretty simple here :
while(!feof(input)){
fscanf(input,"%c",&letter);
putchar(letter);
}
and remember to close file using fclose(input);
Related
I have a file .txt containing some values formatted like this:
0,30,25,10
Now, I open up the file and store it into an array
char imposta_tratt[300];
FILE *fp;
fp = fopen("/home/pi/Documents/imposta_trattamento.txt", "r");
if (fp == 0) return;
fread(imposta_tratt, sizeof(imposta_tratt), 1, fp);
fclose(fp);
Now I expect to have the array filled with my data. I have the values separated by a , so I go on and parse it:
const char delim[2] = ",";
int t=0;
char *token = strtok(imposta_tratt, delim);
while (token!=NULL){
strcpy(tratt[t],token);
token = strtok(NULL, delim);
tratt[t]=token;
t++;
}
Here, referring to what's in the file .txt, I expect to have tratt[0]=0; tratt[1]=30; tratt[2]=25; and so on, but seems like I am missing something since it's not like this.
All I want is to have the values of the txt file stored in single variables. Can someone help?
What you are trying to achieve can simply be done using fgets():
bool read_file_content(const char *filename, const size_t tsizemax, int tratt[tsizemax], size_t *tsize, const char *delim)
{
// Attempt to open filename.
FILE *fp = fopen(filename, "r");
if (!fp) return false; // Return false upon failure.
// Try to read one line. If you have more, you need a while loop.
char imposta_tratt[300];
if (!fgets(imposta_tratt, sizeof imposta_tratt, fp)) {
fclose(fp);
return false;
}
*tsize = 0;
char tmp[300]; // Temporary buffer. Used for conversion into int.
char *token = strtok(imposta_tratt, delim);
while (token && *tsize < tsizemax) {
strncpy(tmp, token, sizeof tmp);
tratt[(*tsize)++] = atoi(tmp);
token = strtok(NULL, delim);
}
fclose(fp);
return true;
}
const char *filename: The file you want to parse.
const size_t tsizemax: The maximum size of your tratt array. It is important to control the size, otherwise your code will have buffer overflow (think of when your file has more than 100 tokens, for example).
int tratt[tsizemax]: The array that will hold the values.
size_t *tsize: The number of tokens read (used in combination of tsizemax).
const char *delim: The delimiter(s), in your case a ,.
This is your main():
int main(void)
{
int tratt[100];
size_t size = 0;
if (!read_file_content("in.txt", 100, tratt, &size, ",")) {
puts("Failed");
return 1;
}
for (size_t i = 0; i < size; ++i)
printf("%d\n", tratt[i]);
}
Output:
0
30
25
10
Suppose "in.txt" has contents
0,30,25,10
The below program uses fscanf to read the integers into the tratt array, one-by-one. As we read integers using fscanf, we make sure it's return value is as expected. If not, we close the file and exit. In the event that the return value of fscanf is not as expected, the program also prints which type of error occurred. Currently, if any error occurs, the program stops. However, you can make the program behave differently depending on the error that occurred if you like.
As output, the program prints all of the integers read into the tratt array. The output is
0
30
25
10
Now this program assumes we know the number of elements we want to read into tratt. If we do not, we could allow for dynamically allocating more memory should the array need more elements or perhaps "in.txt" could contain a data structure, say, at the beginning/end of the file that records information about the file, such as the number of numbers in the file and the data type (a binary file would be best suited for this). These are just a couple of the possibilities.
A better approach might be to read characters in one-by-one (say, using getc) and use strtol to convert a sequence of character digits to a long int (I would have taken an approach similar to this).
Nevertheless, this approach is more succinct and should suffice.
#include <stdio.h>
#include <stdlib.h>
#define FILE_NAME "in.txt"
#define MAX_LEN 4
int main(void) {
int i, tratt[MAX_LEN];
FILE *fp = fopen(FILE_NAME, "r"); /* open file for reading */
/* if cannot open file */
if (fp == NULL) {
printf("Cannot open %s\n", FILE_NAME);
exit(EXIT_FAILURE);
}
/* read integer, checking return value of scanf as expected */
if (fscanf(fp, "%d", &tratt[0]) != 1) {
if (ferror(fp))
printf("fscanf: read error\n");
else if (feof(fp))
printf("fscanf: end of file\n");
else
printf("fscanf: matching failure\n");
fclose(fp);
exit(EXIT_FAILURE);
}
for (i = 1; i < MAX_LEN; i++)
/* read comma plus integer, checking return value of scanf */
if (fscanf(fp, ",%d", &tratt[i]) != 1) {
if (ferror(fp))
printf("fscanf: read error\n");
else if (feof(fp))
printf("fscanf: end of file\n");
else
printf("fscanf: matching failure\n");
fclose(fp);
exit(EXIT_FAILURE);
}
fclose(fp); /* close file */
/* print integers stored in tratt */
for (i = 0; i < MAX_LEN; i++)
printf("%d\n", tratt[i]);
return 0;
}
I have a list of columns containing text but I just to fetch first upper row from this list. How to do that?
#include <stdio.h>
int main()
{
FILE *fr;
char c;
fr = fopen("prog.txt", "r");
while( c != EOF)
{
c = fgetc(fr); /* read from file*/
printf("%c",c); /* display on screen*/
}
fclose(fr);
return 0;
}
Your stop condition is EOF, everything will be read to the end of the file, what you need is to read till newline character is found, furthermore EOF (-1) should be compared with int type.
You'll need something like:
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fr;
int c;
if(!(fr = fopen("prog.txt", "r"))){ //check file opening
perror("File error");
return EXIT_FAILURE;
}
while ((c = fgetc(fr)) != EOF && c != '\n')
{
printf("%c",c); /* display on screen*/
}
fclose(fr);
return EXIT_SUCCESS;
}
This is respecting your code reading the line char by char, you also have the library functions that allow you to read whole line, like fgets() for a portable piece of code, or getline() if you are not on Windows, alternatively download a portable version, and, of course you can make your own like this one or this one.
For whatever it's worth, here's an example that uses getline
#include <stdio.h>
int main()
{
FILE *fr;
char *line = NULL;
size_t len = 0;
ssize_t nread;
if (!(fr = fopen("prog.txt", "r"))) {
perror("Unable to open file");
return 1;
}
nread = getline(&line, &len, fr);
printf("line: %s, nread: %ld\n", line, nread);
fclose(fr);
return 0;
}
Some notes:
getline() can automatically allocate your read buffer, if you wish.
getline() returns the end of line delimiter. You can always strip it off, if you don't want it.
It's ALWAYS a good idea to check the status of I/O calls like "fopen()".
just replace EOF as '\n'(new line char). Than your code will read until reaching the new line. Here is what it looks like:
#include <stdio.h>
int main()
{
FILE *fr;
char c = ' ';
fr = fopen("prog.txt", "r");
while(c != EOF && c != '\n')
{
c = fgetc(fr); /* read from file*/
if(c != EOF){
printf("%c",c); /* display on screen*/
}
}
fclose(fr);
return 0;
}
I have not tested it yet but probably work. Please let me know if there is some problem with the code i will edit it.
Edit1:char c; in line 5 is initialized as ' ' for dealing with UB.
Edit2:adding condition (c != EOF) to while loop in line 7, for not giving reason to infinite loop.
Edit3:adding if statement to line 10 for not printing EOF which can be reason for odd results.
It's been years since I programmed in C, and so I've been struggling a lot just to do a simply "get filename & path from stdin, read file, print file to stdout" task, which I know shouldn't be that hard but ya. Here is my code:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int main(void) {
int c;
FILE *file;
//scanf("%s", filename);
char *filename;
filename = (char *)malloc(200 * sizeof(char));
read(STDIN_FILENO, filename, 200);
printf("%s", filename);
file = fopen(filename, "r");
if (file) {
while ((c = getc(file)) != EOF)
putchar(c);
fclose(file);
} else {
printf("File not found.");
}
printf("\n");
return(0);
}
I my code continues to simply print out File not found., when I know for a fact my file path and everything is correct (not only because I literally drop it and past it into terminal from my folder with Mac OSX El Capitan - what a lovely feature, but also) because I had a different version of this program using scanf which found the file and read it perfectly fine, (as you can see I have it commented out on my code).
There is another program I'm writing that just uses this one, and I got rid of the scanf because I think it was negatively affecting other things in that program, so I want to be able to use read()
If anyone has any advice on how I can fix this or why this isn't working, that would be greatly appreciated as I've been at this for hours already and would very much like to move on to my actual program that I need to code!
THANKS A BUNCH
You must remove the '\n' new line character that is being read and stored into the filename buffer.
One of the many was to do it is include string.h and after reading the filename
char *newline = strchr(filename, '\n');
if (newline != NULL)
*newline = '\0';
Also, use fgets() instead of read() because that way the program is more portable. And more importantly, read() will not add the null terminator which is very important in order to use the buffer as a string — to pass it to fopen() for example — correctly. If you want to use read try something like this
ssize_t length;
char filename[200];
length = read(STDIN_FILENO, filename, sizeof(filename) - 1);
if (length <= 0)
return -1; // No input or input error
if (filename[length] == '\n')
filename[--length] = '\0';
else
filename[length] = '\0';
But otherwise, try this which is simpler
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
FILE *file;
char filename[200];
char *newline;
if (fgets(filename, sizeof(filename), stdin) == NULL)
return -1; // Input error / EOF
newline = strchr(filename, '\n');
if (newline) // ? is a newline present?
*newline = '\0';
printf("**%s**\n", filename); // ** will help checking for
// the presence of white spaces.
file = fopen(filename, "r");
if (file) {
int chr;
while ((chr = fgetc(file)) != EOF)
fputc(chr, stdout);
fclose(file);
} else {
printf("File not found.");
}
printf("\n");
return 0;
}
I have a file which contains the files names for every file in a directory. I am trying to open that file, read the file names from it and then open each file. However, I cannot get it to open the files. I have it printing the word it is reading and know it is reading correctly; however, it will not open the file. Any suggestions? My program is below.
#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
FILE *in;
FILE *in2;
char inName[] = "inputfile.txt";
char *inName2;
inName2 = malloc(36 * sizeof (char));
char inPhrase[100];
if (( in = fopen(inName, "r")) == NULL )
{
printf("Can't open %s for reading.\n", inName);
return 2;
}
else
{
fgets(inName2, 36, in);
}
if (( in = fopen(inName2, "r")) == NULL )
{
printf("Can't open %s for reading. \n", inName2);
}
else
{
fgets(inPhrase, 100, in2);
printf("%s\n", inPhrase);
}
fclose(in);
fclose(in2);
return 0;
}
You have one outright typo and one mistake in your code. The line if (( in = fopen(inName2, "r")) == NULL ) should open in2 instead: if (( in2 = fopen(inName2, "r")) == NULL ). Your error message almost certainly reads something like this:
Can't open test_file.txt
for reading
Notice the newline that fgets always reads in for you. You should trim the line somehow. There are a few options available:
If your last line is guaranteed to be newline terminated, you can just remove the last character from each line: strchr(inName2, '\0')[-1] = '\0';.
You can trim the whitespace from the end of each line.
You can delete the last character only if it is \n (or possibly two characters, \r\n on Windows)
Final note: you should always post your error messages. If you were clever enough to interpret it properly in the first place, you would not be posting here, so don't expect us to take your word for where the program failed.
Do it this way
#include <stdio.h>
#include <stdlib.h>
int main() {
char inName[] = "inputfile.txt", * inName2;
FILE * in = fopen(inName, "r"), * in2;
char inPhrase[100];
size_t len;
// Check whether file opened correctly or display error
if (in == NULL) { perror(inName); return 1; }
// Read file line by line
while (getline(&inName2, &len, in) != -1) {
// Check if file opens otherwise go to next file
if ((in2 = fopen(inName2, "r")) == NULL) { perror(inName2); continue; }
// Read 100 chars from each file and display
fgets(inPhrase, 100, in2);
printf("%s\n", inPhrase);
fclose(in2);
}
fclose(in);
return 0;
}
This question already has answers here:
Reading the whole text file into a char array in C
(5 answers)
Closed 8 years ago.
I wrote c code which input value for my program comes from here :
char *input[] = {"This input string value !!!", NULL};
But how can I read this value from the file (e.g. input.txt)? Is it possible to get the file content like a string?
Thanks a lot!
If you want to read a file line-by-line, the easiest way to go is using getline. Read the man page for a detailed description and a good code example.
getline will do all the low-lvel plumbing work of allocating buffers, copying data and scanning for newline characters, etc for you. Keep in mind that this is only possible since getline uses dynamically allocated memory that you'll need to free again.
On recent Posix compliant systems you could use getline(3), something like
FILE *fil = fopen("somefile.txt", "r");
if (!fil) {perror("somefile.txt"); exit(EXIT_FAILURE); };
char*linbuf = NULL;
size_t siz = 0;
ssize_t linlen = 0;
while ((linlen=getline(&linbuf, &siz, fil))>0) {
// linbuf contains the current line
// linlen is the length of the current line
do_something_with(linbuf, linlen);
};
fclose(fil);
free(linbuf), linbuf=NULL;
linlen = 0, siz = 0;
You can use fgets() like this:
#include <stdio.h>
int main(void)
{
char buffer[100];
FILE *file = fopen("input.txt", "r");
// Checks if the file was opened successfully
if (file == NULL)
{
fputs("Failed to open the file\n", stderr);
return -1;
}
// fgets here reads an entire line or 99 characters (+1 for \0) at a time, whichever comes first
while (fgets(buffer, sizeof(buffer), file) != NULL)
{
printf("Line read = %s\n", buffer);
}
fclose(file);
}
You can also use fgetc() like this:
#include <stdio.h>
int main(void)
{
int ch;
FILE *file = fopen("input.txt", "r");
// Checks if the file was opened successfully
if (file == NULL)
{
fputs("Failed to open the file\n", stderr);
return -1;
}
// fgetc reads each character one by one until the end of the file
while ((ch = fgetc(file)) != EOF)
{
printf("Character read = %c\n", ch);
}
fclose(file);
}