Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm making a RPG game in C, and I need to read from a single file. Having multiple files is very tedious. Like "health.dat", "energy.dat", "money.dat" etc. I want to put them into one "data.dat", is this possible?
I just want to read specific line from a file
If line 1 has "number 1", then it should go to the "a" variable, line 2 should go to the "b" variable, etc.
Many thanks.
It is possible.
you can use the array of pointers in the fgets function.
char *fgets(char *s, int size + 1, FILE *stream);
fgets (array,size + 1,stream);
where array is *array[size];
You can achieve what you describe using the fgets function as follows:
#include <stdio.h>
#include <stdlib.h>
const int MAX_LENGTH = 256;
int main (void)
{
// Open the file
FILE* file = fopen ("data.dat", "r");
// Read the lines
char a[MAX_LENGTH];
fgets (a, MAX_LENGTH - 1, file);
char b[MAX_LENGTH];
fgets (b, MAX_LENGTH - 1, file);
// ...
// Close the file
fclose (file);
return EXIT_SUCCESS;
}
Set the MAX_LENGTH variable to the maximum expected length of a line in your file. You should also test fopen and fgets for returning NULL, as both are error conditions.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Here is the code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
FILE *filePointer ;
char dataToBeRead[50];
filePointer = fopen("input.txt", "r") ;
while( fgets ( dataToBeRead, 50, filePointer ) != NULL )
{
printf( "%s" , dataToBeRead ) ;
}
fclose(filePointer) ;
}
And this is the text file enter image description here. I want to take the word in the middle of each line and print it.
You can use
strtok(str, ",")
strtok(NULL, ",")
printf("%s\n", str);
This is not thread-safe or re-entrant but you're unlikely to care about that for this exercise.
If this is too fancy (I assume this is a student exercise and a simpler version may be desired) try stepping through the string character-by-character, counting commas and using putchar during the appropriate section.
As with many tasks in C, there are lots of ways to do this one. One suggestion could be to use the strstr() and snprintf() functions to help find the beginning of the search word then truncate the rest of line to include only the word of interest: (your code modified to use this approach)
while( fgets ( dataToBeRead, 50, filePointer ) != NULL )
{
char *temp = strstr(dataToBeRead, "SearchTerm");
if(temp != NULL)
{
char found[50]={0};
snprintf(found, strlen("searchTerm"), temp)
printf( "%s" , found) ;
}
...
Another way, (simpler, but perhaps not as satisfying) simply test the input buffer for existence of the search term using strstr() (as the above example does), but if strstr() does not return NULL, then simply print out the given search term without bothering to parse its twin from out of the line buffer.
Aside: Magic numbers (Such as 50 in your example: char dataToBeRead[50]; are not as useful as human readable and understandable variables and/or #define values, eg:
#define MAX_FILE_LINE_LEN 50
Then in your code, everywhere 50 would be used, replace it with MAX_FILE_LINE_LEN
And, while on the topic, use a more reasonable length than 50. At least 80, but 260 would not be too big for most systems either.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I would like to display the names of files without their .txt extension. I already have the file + extension stored from dir->d_name.
It made sense in my head to do it the following way:
char filename[size]; //assume this already contains name followed by.txt
filename[size-4] = '\0';
I've attempted this, but I am still getting the name with its extension. Perhaps I don't fully understand how the null terminator works.
Any suggestions?
This:
filename[size-4] = '\0';
will not work, since size is not (necessarily) the length of the string.
Try:
filename[strlen(filename) - 4] = '\0';
Minimal example:
#include <stdio.h>
#include <string.h>
#define SIZE 20
int main(void) {
char filename[SIZE] = "test.txt";
printf("%s\n", filename);
// -4 for .txt
filename[strlen(filename) - 4] = '\0';
printf("%s\n", filename);
return 0;
}
Output:
gsamaras#gsamaras:~$ ./a.out
test.txt
test
PS - You may want to check if .txt really exists.
Or*, by using strstr(), you could do this and check if .txt actually exists:
#include <stdio.h>
#include <string.h>
int main (void) {
char str[] = "test.txt";
char *pch;
pch = strstr(str, ".txt");
if(pch) // if's body won't execute if .txt is absent
*pch = '\0';
puts(str);
return 0;
}
*as #user3386109 said
Trying doing
strncopy(noExt_string, filename, strlen(filename) - 4)
This should copy the contents of filename in to noExt_string without the last 4 characters.
If you only want to print the filename without the .txt extension then you can do it without change the string.
write(1, filename, strlen(filename) - 4);
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
I 12 0
I 9 1
I 26 0
I 25 2
B 26
P 0
R 25
A
So, what I need to do is read a file containing these characters/numbers and whenever I encounter a letter, I call a function to process whatever comes after the letter (aka the numbers).
For example:
When reading "I" I have to call the function to INSERT a certain number in a certain level of a Skip List; or when reading B, I need to search for a specific number in the Skip List, etc.
Problem is I'm really bad at reading from a file, can you guys enlighten me?
You can do this with file operations in c,
i am just giving you hints,
FILE *pFilePtr; // file pointer(handle of file)
pFilePtr = fopen(argv[1],"r");
//define buffer to store data read line by line data
char buf[32]={0};
//Now you can run a while loop to read entire file
with fread() to get whole first line(until '\n')
while(!feof(pFilePtr))
{
if(NULL != fgets(buf,32,pFilePtr))
// perform string operation on buffer to extract letters and digits
// and according to that call functions you need
}
#include <stdio.h>
#include <string.h>
int main(void) {
FILE *fptr;
char mystring[20];
int number;
fptr = fopen("Input.txt", "r");
while(fscanf(fptr , "%s %d", mystring, &number) != EOF) {
printf("%s %d\n", mystring, number);
if(strcmp(mystring, "I") == 0) {
printf("Implement the reqd function here\n");
}
}
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have to parse a text file with 3 different data types. I want it to be saved in a structure array with three members. My text file look like this:
A B 45.78965
A C 35.46731
B C 46.78695
The program that I'm reading it with is the following and it does not work.
What am I doing wrong?
#include <stdio.h>
struct gra {
char from;
char to;
double w;
};
int main ()
{
FILE *fp = fopen("graph.txt", "r");
int i = 0;
while (!feof(fp)) {
fscanf(fp, "%[^\t]", &graph[i].from, &graph[i].to, &graph[i].w);
i++;
}
fclose(fp);
}
One of your problems is that you're reading using %[^\t], which reads strings, and store the result to variables that are not character arrays (two characters and a double).
Although it's not clear from your question, it seems that the lines of your input contain two characters and one real number separated by one tab character. If that is so, you should use the following fscanf to read them:
fscanf(fp, "%c\t%c\t%lf\n", &graph[i].from, &graph[i].to, &graph[i].w);
If you are not sure what exactly separates your fields and you want to allow any amount of white space in between and also extra white space in the beginning and end of the line, then use:
fscanf(fp, " %c %c%lf\n", &graph[i].from, &graph[i].to, &graph[i].w);
that is, use an extra space in the format before each "%c" to explicitly skip white space.
Your code has also a couple of other problems:
You are using feof to check for end of file. This will usually not work well if you're not reading the file character by character. Instead, you should check if your fscanf returned 3, that is, if it successfully read the three things that you wanted it to read.
You are missing a definition of array graph.
I'm adding the complete code that I'd write for doing the parsing:
#include"stdio.h"
#define MAX 100
struct {
char from, to;
double w;
} graph[MAX];
int main ()
{
FILE *fp = fopen("graph.txt", "rt");
for (int i=0; i<MAX; i++)
if (fscanf(fp, " %c %c%lf\n", &graph[i].from, &graph[i].to, &graph[i].w) < 3)
break;
fclose(fp);
return 0;
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
And I want it to print to output as is. Curently I am using this code
#include <stdio.h>
#include <ctype.h>
#define BUFFER_SIZE 2000
int main(void)
{
char buffer[BUFFER_SIZE];
while(fgets (buffer, BUFFER_SIZE, stdin) !=NULL)
{
printf("%s",buffer);
}
return 0;
}
Then I want the program to be able to skip html tags in the original text but I don't know exactly how to work around that.
You should use getline(3) (at least on Posix compliant systems). Your fgets based code won't work with very long lines (because a very long line would be "truncated": all of it would be read, but only BUFFER_SIZE characters would have been copied, and the rest of the line ignored).
You could code
char* linebuf=NULL;
size_t linesize=0;
while (!feof(stdin)) {
ssize_t linelen = getline(&linebuf, &linesize, stdin);
if (linelen<0) { perror("getline"); exit(EXIT_FAILURE); };
fputs(linebuf, stdout);
}
In the above code, the linebuf will (unless failure) be grown to the widest line size. You should free(linebuf) after that loop...