My professor gave us the code to get input from a text file. The issue is it will not compile properly for me. I'm not sure where he (or I) went wrong. I have not modified his code in any way and my txt file is in the same directory as the code.
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp;
char ch;
fp = fopen("IronHeelShort.txt", "r");
printf("Data inside file : ");
while(1)
{
ch = fgetc(fp);
printf("%c", ch);
if (ch == EOF)
break;
}
getch();
}
chshould be an int anyway
The function fgetc() will always return an int, to handle all the char values and EOF which is negative.
Here reading your file will prematurely end when finding character 0xFF.
For the compiling issue, change getch() into getchar()
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
int main()
{
FILE *fp;
char ch;
fp = fopen("C:/emule/c/0.html", "r");
printf("Data inside file : ");
while (1)
{
ch = fgetc(fp);
printf("%c", ch);
if (ch == EOF)
break;
}
_getch();
}
UPD
#include <stdio.h>
#include <stdlib.h>
void main() {
FILE *input = NULL;
char c;
input = fopen("D:/c/text.txt", "rt");
if (input == NULL) {
printf("Error opening file");
scanf("1");
exit(0);
}
while (fscanf(input, "%c", &c) == 1) {
fprintf(stdout, "%c", c);
}
fclose(input);
scanf("1");
}
Related
main.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "function.h"
int main()
{
int nl, nw, nc;
nl = nw = nc = 0;
char filename[100];
printf("ENTER FILE NAME: ");
scanf("%s", filename);
FILE *fp = fopen(filename, "r");
if(fp == NULL)
{
printf("OPEN FAIL");
exit(0);
}
nc = character(fp);
nw = word(fp);
nl = line(fp);
printf("number of characters: %d\n", nc);
printf("number of words: %d\n", nw);
printf("number of lines: %d\n", nl);
fclose(fp);
return 0;
}
character.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int character(FILE *fp)
{
int nc = 0;
char ch;
while((ch=fgetc(fp)) != EOF)
{
if(ch != ' ' && ch != '\t' && ch != '\n' && ch != '\0')
{
nc++;
}
}
return nc;
}
word.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int word(FILE *fp)
{
int nw = 0;
char ch;
while((ch=fgetc(fp)) != EOF)
{
if(ch == ' ' || ch == '\t' || ch == '\n' || ch == '\0')
{
nw++;
}
}
return nw;
}
line.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int line(FILE *fp)
{
int nl = 0;
char ch;
while((ch=fgetc(fp)) != EOF)
{
if((ch == '\n' || ch == '\0'))
{
nl += 1;
}
}
return nl;
}
function.h
int line(FILE *fp);
int word(FILE *fp);
int character(FILE *fp);
execution results
ENTER FILE NAME: test.txt
number of characters: 36
number of words: 0
number of lines: 0
My program counts the number of characters correctly but not of the words nor lines.
It seems strange to me because I think that the basic structure of codes for word and line counter shouldn't be so different from that for the characters.
I think that I only have to change the conditions of the if when I count the numbers of words and lines.
Most of all, at least, the program should give me some number other than mere zeros since the text file definitely contains spaces and new lines.
What do you think the problems here?
FYI the text file I used for testing is
test test test
test test test
test test test
Once you have called the character function, the file is at its end. The next attempt to read from the file will result in EOF.
You need to seek back to the beginning again if you want to start reading it all over.
On another couple of notes, first remember that fgetc return an int, which is rather important for the comparison against the int value EOF.
Secondly you don't need three different function and three different loops. You can count all statistics in one single loop.
#include <stdio.h>
#include <stdlib.h>
int process_stream(FILE *fpntr);
char *fgetline(FILE *fpntr);
int main(int argc, char* argv[]) {
FILE *fpntr;
char filename[100], c;
int a = 0;
printf("Please enter a file name/directory: \n");
scanf("%s", filename);
fpntr = fopen(filename, "r");
if (fpntr == NULL) {
printf("cannot open file \n");
exit(0);
}
//read contents from file
c = fgetc(fpntr);
while (c != EOF){
printf ("%c", c);
c = fgetc(fpntr);
if (c == '\n')
{
a++;
printf("%d", a);
}}
fclose(fpntr);
return 0;
exit (0);
}
Firstly, implement just as what you says.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char* argv[]) {
FILE *fptr;
char filename[100];
int c;
int lineNumber = 1;
printf("Please enter a file name/directory: \n");
scanf("%99s", filename);
// Open the file
fptr = fopen(filename, "r");
if (fptr == NULL) {
printf("cannot open file \n");
exit(0);
}
//read contents from file
// While ((c = read a character) is not EOF)
while ((c = fgetc(fptr)) != EOF){
// If (c is \n)
if (c == '\n') {
// Print "lineNumber", then increment it
printf("%d. ", lineNumber);
lineNumber++;
}
// Print c
printf ("%c", c);
// End while
}
// Close the file
fclose(fptr);
return 0;
}
Unfortunately, this code won't work well and its output is
#include <stdio.h>1.
#include <stdlib.h>2.
int hoge;3.
int fuga;4.
when the input file is
#include <stdio.h>
#include <stdlib.h>
int hoge;
int fuga;
The fault is that you are printing line numbers at the end of lines.
They should be at the beginning of lines.
I would use a flag that indicates beginning of lines.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char* argv[]) {
FILE *fptr;
char filename[100];
int c;
int lineNumber = 1;
int isBeginningOfLine = 1;
printf("Please enter a file name/directory: \n");
scanf("%99s", filename);
fptr = fopen(filename, "r");
if (fptr == NULL) {
printf("cannot open file \n");
exit(0);
}
//read contents from file
while ((c = fgetc(fptr)) != EOF){
if (isBeginningOfLine) {
print("%d. ", lineNumber);
isBeginningOfLine = 0;
}
if (c == '\n') {
lineNumber++;
isBeginningOfLine = 1;
}
printf ("%c", c);
}
fclose(fptr);
return 0;
}
Now I get
1. #include <stdio.h>
2. #include <stdlib.h>
3. int hoge;
4. int fuga;
can you tell me what adjustments i can do for my code, or any simplifications? What shouldn't
i repeat, what should i change ? This code converts every word to upper case, if you find some problems,pls write in order to fix it))
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main(){
FILE * fPtr, *fPtr1;
int c; /*to store characters*/
char filename[20];
char filename2[20] = "temp.txt";
printf("Enter name of file: ");
scanf("%19s%*c",filename);
fPtr = fopen(filename, "r");
fPtr1 = fopen(filename2, "w");
c = fgetc(fPtr);
while(c!=EOF){
if(c!='\n'){
if(islower(c)){
fputc(c-32,fPtr1);
}else{
fputc(c,fPtr1);
}
}else{
fputc(c,fPtr1);
}
c = fgetc(fPtr);
}
fclose(fPtr);
fclose(fPtr1);
remove(filename);
rename(filename2,filename);
fPtr = fopen(filename, "r");
c = fgetc(fPtr);
while(c!=EOF){
printf("%c",c);
c = fgetc(fPtr);
}
fclose(fPtr);
}
This program does what you say it does. But I recommend some changes that your future self will appreciate.
First, always initialize your variables; this habit will help to prevent odd bugs in your future code. Set ints to a value out of your expected range (e.g. maybe -1 in this case); set pointers to NULL; set char arrays to { '\0' } or to "\0".
Next, check your file pointers (fPtr, fPtr1) for NULL after fopen.
Finally, specific to this code, your check for new-line is unnecessary; islower will return 0 if the parameter is not a lowercase alphabetic character.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define MAX 20
char *mygets(char *s, size_t sz) {
int ch;
size_t i = 0;
while((ch = getchar()) != '\n' && i < sz)
s[i++] = ch;
s[i] = '\0';
return s;
}
int main(void) {
FILE *fPtr;
char filename[MAX+1];
int c, i;
printf("Enter name of file: ");
mygets(filename, MAX+1);
if(!strstr(filename, ".txt"))
strcat(filename, ".txt");
if((fPtr = fopen(filename, "r+")) == NULL) {
fprintf(stderr, "Could not open %s\n", filename);
exit(1);
}
i = 0;
while((c = fgetc(fPtr)) != EOF) {
fseek(fPtr, i, SEEK_SET);
fputc(toupper(c), fPtr);
i++;
}
rewind(fPtr);
while((c = fgetc(fPtr)) != EOF)
putchar(c);
fclose(fPtr);
return 0;
}
In my program, I can currently read char by char a file with given name "fichier1.txt", but what I'm looking for is to store a line(line char pointer here) and then display it that way :
-ligne 1 : content line 1
-line 2 : content line 2
-ect...
I've tried to store char by char but since it's a pointer and I'm yet that much familiar with pointers I'm not able to store a line and then reuse the pointer to store the char of the next line.
I have to say that it's part of a school projet and I have to use POSIX standard.
#include<stdio.h>
#include<stdlib.h>
#include<errno.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
#include <pthread.h>
#include<string.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(){
int read_fd, write_fd;
off_t offset = 0;
char lu;
struct stat statFd;
char *fichier = "fichier1.txt";
read_fd = open(fichier,O_RDONLY);
stat(fichier, &statFd);
if(read_fd == -1){
perror("open");
exit(EXIT_FAILURE);
}
int i = 0;
char * line; // variable to store line
while(lseek(read_fd,offset, SEEK_SET) < statFd.st_size)
{
if(read(read_fd, &lu, 1) != -1)
{
printf("%c",lu);
offset++;
} else {
perror("READ\n");
close(read_fd);
close(write_fd);
exit(EXIT_FAILURE);
}
}
return 0;
}
I'd like to use open() function and not fopen()
Since you are able to read character after character from the file, the logic in while loop will be used to store an entire line (up to 199 characters, you can increase it though) at once in an array & then display it:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main(void)
{
FILE *fptr=fopen( "fichier1.txt","r");
int i;
char arr[200]; //THIS ARRAY WILL HOLD THE CONTENTS OF A LINE TEMPORARILY UNTIL IT IS PRINTED
int temp_index=0,line_number=1;;
memset(arr,'\0',sizeof(arr));
while((i=getc(fptr))!=EOF)
{
if(i!='\n')
{
arr[temp_index++]=i;
}
if(i=='\n')
{
printf(line %d: %s\n",line_number++,arr);
temp_index=0;
memset(arr,'\0',sizeof(arr));
}
}
return 0;
}
Calling lseek at every iteration may be inefficient and may fail on devices which are incapable of seeking. I would write a program along these lines below if I don't need to store lines.
#include <stdio.h>
#include <stdlib.h>
int main (void)
{
int lc = 0; /* line count */
int c; /* character read */
FILE *fp = fopen("fichier1.txt", "r");
if (fp == NULL) {
perror("fopen");
return EXIT_FAILURE;
}
while ((c = fgetc(fp)) != EOF) {
printf("line %d: ", ++lc);
while (c != '\n' && c != EOF) {
putchar(c);
c = fgetc(fp);
}
putchar('\n');
}
return 0;
}
Or, a program using fgets to read a line at once:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
int main (void)
{
int lc = 0; /* line count */
char buf[4096]; /* buffer to store the line read */
bool newline = true;
FILE *fp = fopen("fichier1.txt", "r");
if (fp == NULL) {
perror("fopen");
return EXIT_FAILURE;
}
while (fgets(buf, sizeof buf, fp) != NULL) {
if (newline)
printf("line %d: ", ++lc);
printf("%s", buf);
newline = strchr(buf, '\n');
}
return 0;
}
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX 500
int main(){
int JourneyId;
char Date[MAX];
int Hour;
char BusDriver[MAX];
char Departure[MAX];
char Destination[MAX];
int BusCapacity;
FILE * file;
file = fopen( "Journey.txt" , "rt");
if(file){
while (fscanf(file,"%d,%s,%d,%20[^,],%20[^,],%20[^,],%d", &JourneyId,Date,&Hour,BusDriver,Departure,Destination, &BusCapacity) != EOF){
printf("%d,",JourneyId);
printf("%s",BusDriver);
}
}
else{
printf("Error");
}
return 1;
}
I want to read text file and use this code for adding BST.But If I run , Output is infinite loop.How can I read text file ?
Text file which I want to read:
80,15.04.2014,10,Henry Ford,NewYork,Paris,45
40,15.04.2014,11,Nikola Tesla,Londra,NewYork,40
Rather than read a text file using fscanf(), strongly recommend using fgets() and then parsing via sscanf(), strtok(), strtol(), etc. Check all function return values. It is much easier to cope with the unexpected - which is certainly what is happening in OP's case.
Using modified format from #BLUEPIXY
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX 500
int main() {
int JourneyId;
char Date[MAX];
int Hour;
char BusDriver[MAX];
char Departure[MAX];
char Destination[MAX];
int BusCapacity;
FILE * file;
file = fopen("Journey.txt", "rt");
if (file) {
char buf[MAX*4 + 20*3 + 6*1 + 3];
while (fgets(buf, sizeof buf, stdin) != NULL) {
int cnt = sscanf(buf, "%d,%499[^,],%d,%499[^,],%499[^,],%499[^,],%d",
&JourneyId, Date, &Hour, BusDriver, Departure, Destination,
&BusCapacity);
if (cnt != 7) {
printf("Unexpected input \"%s\"", buf);
break;
}
printf("%d,", JourneyId);
printf("%s\n", BusDriver);
}
fclose(file); // Be sure to close
} else {
printf("Error opening\n");
}
return 1;
}
As #BLUPIXY indicated, The following functions (tried on SuSE Linux / gcc)
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX 500
int main(){
int JourneyId;
char Date[MAX];
int Hour;
char BusDriver[MAX];
char Departure[MAX];
char Destination[MAX];
int BusCapacity;
FILE *file;
file = fopen( "Journey.txt" , "rt");
if(file)
{
// while(fscanf(file,"%d,%s,%d,%20[^,],%20[^,],%20[^,],%d", &JourneyId,Date,&Hour,BusDriver,Departure,Destination, &BusCapacity) != EOF){
while(fscanf(file,"%d,%11[^,],%d,%20[^,],%20[^,],%20[^,],%d", &JourneyId,Date,&Hour,BusDriver,Departure,Destination, &BusCapacity) != EOF){
printf("%d,",JourneyId);
printf("%s",BusDriver);
}
}
else
{
printf("Error");
}
return 1;
}