I am trying to parse through a line a line of text from a .txt file and set it to a string. It is parsing most of the lines, except for the first 4 characters. This is what I'm trying to parse:
12X6 de8 dw3 ds5 g8,7 m3,4 p2,2 h2,2
And this is my code:
FILE * rooms;
int i;
char c;
char roomString[ROOM_STRING_LENGTH];
rooms = fopen("assets/rooms.txt", "r");
if(rooms == NULL)
{
printf("error opening file\n");
}
fscanf(rooms, "%s", roomString);
while((c=fgetc(rooms))!='\n')
{
roomString[i] = c;
i++;
}
printf("%s\n", roomString);
Your fscanf() call consumes the first word of the input. Remove that call.
if(rooms == NULL)
{
printf("error opening file\n");
}
//fscanf(rooms, "%s", roomString);
while((c=fgetc(rooms))!='\n')
Why do you do fscanf when you are doing fgetc. This fscanf increments the file pointer to the next word. Remove the fscanf and execute your code with the mentioned changes.
#include<stdio.h>
#define ROOM_STRING_LENGTH 50
void main(){
FILE* rooms;
int i =0;
char c;
char roomString[ROOM_STRING_LENGTH];
rooms = fopen("rooms.txt", "r");
if(rooms == NULL)
{
printf("error opening file\n");
}
//fscanf(rooms, "%s", roomString);
//printf("%s\n", roomString);
while((c=fgetc(rooms))!='\n')
{
roomString[i] = c;
i++;
}
roomString[i] ='\0';
printf("%s\n", roomString);
}
Related
I want to pass the file pointer as an argument to view function. And then I want to get the output the data on file from the view function. But every time telling me file not found.
#include<stdio.h>
void view(FILE *file){
char c;
file=fopen(file,"r");
if(file==NULL){
printf("file not found");
}
else{
while(!feof(file)){
c=fgetc(file);
printf("%c",c);
}
fclose(file);
}
}
int main(){
FILE *file;
file=fopen("hello.txt","w");
char s[]="hello world";
fprintf(file,"%s",s);
fclose(file);
printf("Enter 1 to read file");
int n;
scanf("%d",&n);
if(n==1)
view(file);
return 0;
}
Your error is here:
file=fopen(file,"r");
Use something like this:
file=fopen("file name","r");
As already stated in the comments, and in this answer, the fopen argument is wrong, you pass a pointer to file when you should pass the file path.
Other than that you could refactor your code so that you wouldn't have to close and reopen the file:
void view(FILE *file)
{
// the file is already opened, no need to reopen it
int c;
while ((c = fgetc(file)) != EOF) // better read routine
{ // you could also use fgets to read the whole line
printf("%c", c);
}
fclose(file);
}
int main()
{
FILE *file;
file = fopen("hello.txt", "w+"); // open to write and read
int n;
char s[] = "hello world";
if (file == NULL)
{
printf("file not found"); // perror("fopen"); would be better
return EXIT_FAILURE; // #include <stdlib.h>
}
fprintf(file, "%s", s);
printf("Enter 1 to read file: ");
if (scanf("%d", &n) == 1)
{
if (n == 1)
{
rewind(file); // reset file pointer offset to the beginning
view(file);
}
}
}
I need to scan values from .txt to a structure so I can work further on with my program. I've been trying various methods from the thread and this is the closes I got to a successful build.
I can NOT get the values to be printed out so I can test if they scanned correctly before working my way further into the program.
I have different values in struct:
struct knyga
{
char vardas[10];
char pavadinimas[50];
int metai;
double kaina;
};
and this is my reading function:
void Skaitymas(struct knyga arr_knyga[]){
FILE *fp;
fp = fopen("duomenys.txt", "r");
int skaicius;
int txt;
txt = fgetc(fp);
while((txt = fgetc(fp)) != EOF){
if(txt == '\n') skaicius++;
txt = fgetc(fp);
}
printf("%d", skaicius);
fp = fopen("duomenys.txt", "r");
for(int i = 0; i < skaicius; i++){
fscanf(fp, "%s %s %d %lf", arr_knyga[i].vardas, arr_knyga[i].pavadinimas, &arr_knyga[i].metai, &arr_knyga[i].kaina);
}
fclose(fp);
}
EDIT:
This is the content of my text file:
Onute Knyga 1999 12.12
Petras Knygute 2001 9.99
EDIT 2:
my main function:
int main() {
struct knyga arr_knyga[10];
Skaitymas(arr_knyga);
return 0;
}
You call txt = fgetc(fp); too often. The two occurrences of this line must be removed.
Especially in the loop you have one call to fgetc that is checked for '\n' and a second call that is not checked, so there is a 50%/50% chance that a '\n' is not counted.
You forgot to initialize the counter variable.
The counting would be correct with this version:
void Skaitymas(struct knyga arr_knyga[]){
FILE *fp;
fp = fopen("duomenys.txt", "r");
int skaicius = 0;
int txt;
while((txt = fgetc(fp)) != EOF){
if(txt == '\n') skaicius++;
}
printf("%d", skaicius);
fclose(fp);
}
But it would be better to omit the line-counting and detect the end-of-file condition in the fscanf loop.
void Skaitymas(struct knyga arr_knyga[]){
FILE *fp;
fp = fopen("duomenys.txt", "r");
int skaicius = 0;
int rc;
while(1)
{
rc = fscanf(fp, "%s %s %d %lf", arr_knyga[skaicius].vardas, arr_knyga[skaicius].pavadinimas, &arr_knyga[skaicius].metai, &arr_knyga[skaicius].kaina);
if(rc == 4)
{
skaicius++;
}
else
{
break;
}
}
if(!feof(fp))
{
fprintf(stderr, "error reading file or wrong data after line %d\n", skaicius);
}
else
{
printf("%d", skaicius);
}
fclose(fp);
}
I want to write code were the user is asked to write the name of a file. Then I want to analyze the file's content for a symbol, let's say 'e'.
My problem is that I don't know how to start analyzing the file the correct way so that the content can be checked.
int main() {
char c[1000], file_name[1000];
int i;
int s = 0;
FILE *fp;
printf("Enter the name of file you wish to see\n");
gets(file_name);
if ((fp = fopen(file_name, "r")) == NULL){
printf("Error! opening file");
exit(1);
}
if (fp) {
while (fscanf(fp, "%s", c) != EOF) {
printf("%s", c);
}
fclose(fp);
for (i = 0; c[i] != '\0'; ++i) {
puts(c);
if (c[i] == 'e') {
++s;
}
}
printf("\nWhite spaces: %d", s);
_getche();
return 0;
}
}
char line[512]; /*To fetch a line from file maximum of 512 char*/
rewind(fp);
memset(line,0,sizeof(line)); /*Initialize to NULL*/
while ( fgets(line, 512, fp ) && fp !=EOF)
{
/*Suppose u want to analyze string "WELL_DONE" in this fetched line.*/
if(strstr(line,"WELL_DONE")!=NULL)
{
printf("\nFOUND KEYWOD!!\n");
}
memset(line,0,sizeof(line)); /*Initialize to null to fetch again*/
}
If its just a symbol you're looking for, or a char, you can simply use getc() :
int c;
....
if (fp) {
while ((c = getc(fp)) != EOF) {
if (c == 'e') {
// Do what you need
}
}
Or, alternatively, if it's a word you're looking for, fscanf() will do the job:
int c;
char symb[100];
char symbToFind[] = "watever"; // This is the word you're looking for
....
while ((c = fscanf(fp, %s, symb)) != EOF) {
if (strcmp(symb, symbToFind) == 0) { // strcmp will compare every word in the file
// do whatever // to symbToFind
}
}
These alternatives will allow you to search every char or string in the file, without having to save them as an array.
void main()
{
FILE *fp1;
char ch;
int count = 0;
fp1 = fopen("Text.txt","r");
if(fp1==NULL){
printf("Failed to open file. Bye\n");
exit(1);
}
printf("Text file exists");
fclose(fp1);
}
example of an input file(Text.txt)-
3
nameA
nameB
nameC
I would like to check if the very first character of this input file is a number. If its missing a number than program will stop
Include ctype.h and then there are functions that do type checks. Alternatively check if the value of the char is in the appropriate ASCII range.
This would solve your problem
void main()
{
FILE *fp1;
char ch;
int count = 0;
fp1 = fopen("Text.txt","r");
if(fp1==NULL){
printf("Failed to open file. Bye\n");
exit(1);
}
printf("Text file exists");
ch = fgetc(fp1);
if (ch < '0' || ch > '9') {
fclose(fp1);
printf("Exit: First character is not a number\n");
return; // first character of the input file is not number so exit
}
fclose(fp1);
}
#include <stdio.h>
#include <stdlib.h>
int main(){
FILE *fp1;
char ch, line[128];
int count = 0, num;
fp1 = fopen("Text.txt","r");
if(fp1==NULL){
printf("Failed to open file. Bye\n");
exit(1);
}
printf("Text file exists\n");
if(fgets(line, sizeof(line), fp1)){
if(1==sscanf(line, "%d", &num)){
while(num-- && fgets(line, sizeof(line), fp1)){
printf("%s", line);
}
} else {
printf("The beginning of the file is not numeric. Bye\n");
exit(1);
}
} else {
printf("No contents of the file. Bye\n");
exit(1);
}
fclose(fp1);
return 0;
}
here's the code in question:
FILE *fp;
char str[256];
/* opening file for reading */
fp = fopen("file.txt" , "r");
if(fp == NULL) {
perror("Error opening file");
return(-1);
}
while( fgets (str, sizeof(str), fp)) {
int i;
char *temp;
temp=malloc(257);
for(i=0;i<sizeof(str)-1;i++){
if(isalpha(str[i])){
append(temp,str[i]);
}else{
printf(" %s ",temp);
temp=calloc(257,sizeof(char));
}
}
}
if the text file is the following:
"Here's a text
file example. No
idea what's wrong."
then it will output the following:
"Here s a text vf file example No vf idea what s wrong".
Desired output for reference:
"Here s a text file example No idea what s wrong"
Basically some weird stuff every time there's a newline involved. Could be "vf" when i run it. Could be "ZG" the next time. It changes every time i run the program.
Reading parts of buf not filled by fgets()`.
Replace
// for(i=0;i<sizeof(str)-1;i++)
for(i=0;i<strlen(str);i++)
or better
// for(i=0;i<sizeof(str)-1;i++)
size_t len = strlen(str);
// removed potenital ending '\n'
if ((len > 0) && (str[len-1] == '\n')) len--;
size_t i;
for (i = 0; i < len; i++)
Perhaps I didn't understand what you're doing but if you just want to read the whole file in one string you can do something like this
int main(int argc, const char * argv[])
{
FILE *fp;
char str[256];
char *temp = calloc(257, 1);
fp = fopen("file.txt" , "r");
if(fp == NULL) {
perror("Error opening file");
return(-1);
}
while( fgets (str, sizeof(str), fp)) {
int i;
//char *temp;
if (str[strlen(str)-1] == '\n') {
str[strlen(str)-1] = ' ';
}
strncat(temp, str, 257);
}
puts(temp);
}
There is no problem with fgets. It automatically appends terminating null character.
Also you do not free memory before allocating new. It's not good.
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp;
char str[256];
/* opening file for reading */
fp = fopen("file.txt" , "r");
if(fp == NULL) {
perror("Error opening file");
return(-1);
}
while( fgets (str, sizeof(str), fp)) {
int i;
char temp[256]; //buffer; can allocate on the stack, no need for malloc
char *temp1; //pointer at the beginning of the buffer (used to do my own append())
temp1=temp; //for my own appending
for(i=0;i<sizeof(str);i++){
int ch=str[i]; //alias the str[i]
if(isalpha(ch)||ch=='"'){ //let these chars thru
*temp1++=ch; //my own append()
}else if(ch=='\0'){//already at the end of buffer, end loop and print
*temp1=ch; //don't forget to end the string with '\0' (for printing functions)
break;
}else if(ch=='.'){ // you seem to want to skip dots
continue;
}
else {
*temp1++=' '; //replace other nonalpha characters with ' '
}
}
printf("%s",temp);
}
}