I have written a small program to read in a series of strings from a file and then to store them in a 2D Arrray. The strings are read into the array correctly, yet my program is not countering the number of rows in the file like I had expected.
I am honestly at a loss and cannot figure out why the program is not counting the rows in the file. Any explanation as to what I am doing wrong is greatly appreciated.
Here is the code that I have so far:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
FILE* fp;
char nameArray[20][120], str[20];
int i = 0, j = 0, n;
int count = 0;
char name[20]; //filename
int ch;
printf("Please enter a file name: ");
scanf("%s", &name);
fp = fopen(name, "r");
if (fp == NULL) {
printf("File \"%s\" does not exist!\n", name);
return -1;
}
while (fscanf(fp, "%s", str) != EOF)
{
strcpy(nameArray[i], str);
i++;
}
while ((ch = fgetc(fp)) != EOF) {
if (ch == '\n')
count++;
}
for (i = 0; i<=count; i++)
{
printf("%s", nameArray[i]);
}
fclose(fp);
return 0;
}
Related
Here's my task and below you can find my specific question and the code I wrote:
Write a program that reads strings and writes them to a file. The string must be dynamically
allocated and the string can be of arbitrary length. When the string has been read it is written to the
file. The length of the string must be written first then a colon (‘:’) and then the string. The program
stops when user enters a single dot (‘.’) on the line.
For example:
User enters: This is a test
Program writes to file: 14:This is a test
Question:
My code adds the number of characters and the colon, but not the string I typed, and when entered "." it wont exit
This is the code I have so far:
#pragma warning(disable: 4996)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_NAME_SZ 256
int main() {
char key[] = ".";
char *text;
int i;
text = (char*)malloc(MAX_NAME_SZ);
FILE* fp;
do {
printf("Enter text or '.' to exit: ", text);
fgets(text, MAX_NAME_SZ, stdin);
for (i = 0; text[i] != '\0'; ++i);
printf("%d: %s", i);
fp = fopen("EX13.txt", "w");
while ((text = getchar()) != EOF) {
putc(text, fp);
}
fclose(fp);
printf("%s\n", text);
} while (strncmp(key, text, 1) != 0);
puts("Exit program");
free(text);
return 0;
}
There are many issues in your code, almost everything is wrong.
Just a few problems:
You use printf("%d: %s", i); to print on the screen what should go into the file.
The loop while ((text = getchar()) != EOF) doesn't make any sense.
You're closing the file after the first line entered
You ignore all compiler warnings
The end condition while (strncmp(key, text, 1) != 0) is wrong, you're only testing if the string starts with a ., and you're testing it too late.
This could be a start:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_NAME_SZ 256
int main() {
char* text;
int i;
text = (char*)malloc(MAX_NAME_SZ);
FILE* fp;
fp = fopen("EX13.txt", "w");
if (fp == NULL)
{
printf("Can't open file\n");
exit(1);
}
do {
printf("Enter text or '.' to exit: ");
fgets(text, MAX_NAME_SZ, stdin);
if (strcmp(".\n", text) == 0)
break;
for (i = 0; text[i] != '\0' && text[i] != '\n'; ++i);
fprintf(fp, "%d: %s", i, text);
} while (1);
fclose(fp);
puts("Exit program");
free(text);
return 0;
}
There is a limitation though, in this program the maximum line length is 254 characters, not including the newline character. As far as I understood, the line length must be arbitrary.
I let you do this on your own as an exercise, but at your C knowledge level it will be hard.
I think this should work for strings that are shorter than 255 chars.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_NAME_SZ 256
int main()
{
char key[] = ".\n";
char *text;
text = (char*)malloc(MAX_NAME_SZ);
if (text == NULL)
{
perror("problem with allocating memory with malloc for *text");
return 1;
}
FILE *fp;
fp = fopen("EX13.txt", "w");
if (fp == NULL)
{
perror("EX13.txt not opened.\n");
return 1;
}
printf("Enter text or '.' to exit: ");
while (fgets(text, MAX_NAME_SZ, stdin) && strcmp(key, text))
{
fprintf(fp, "%ld: %s", strlen(text) - 1, text);
printf("Enter text or '.' to exit: ");
}
free((void *) text);
fclose(fp);
puts("Exit program");
return 0;
}
#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;
I have written a C program that opens a text file and compares the given string with the string present in the file. I'm trying to print the line number in which the same string occurs, but I am unable to get the proper output: output does not print the correct line number.
I would appreciate any help anyone can offer, Thank you!
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
int main() {
int num = 0, line_number = 1;
char string[50];
char student[100] = { 0 }, chr;
while (student[0] != '0') {
FILE *in_file = fopen("student.txt", "r");
if (in_file == NULL) {
printf("Error file missing\n");
exit(1);
}
printf("please enter a word \n");
scanf("%s", student);
while (fscanf(in_file, "%s", string) == 1) {
if (chr == '\n') {
if (strstr(string, student) == 0) {
break;
} else
line_number += 1;
}
}
printf("line number is: %d\n", line_number);
fclose(in_file);
}
return 0;
}
You cannot read lines with while (fscanf(in_file, "%s", string), the newlines will be consumed by fscanf() preventing you from counting them.
Here is an alternative using fgets():
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char string[200];
char student[100];
int num = 0, line_number = 1;
FILE *in_file = fopen("student.txt", "r");
if (in_file == NULL) {
printf("Error file missing\n");
exit(1);
}
printf("please enter a word \n");
if (scanf("%s", student) != 1) {
printf("No input\n");
exit(1);
}
while (fgets(string, sizeof string, in_file)) {
if (strstr(string, student)) {
printf("line number is: %d\n", line_number);
}
if (strchr(string, '\n')) {
line_number += 1;
}
fclose(in_file);
}
return 0;
}
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;
}
again. I'm new to C. Still thinking in Python terms (readlines, append them to variable) so I'm having difficulties translating that to C. This is what I want to do: open a text file for reading, store each line in an array row by row, print it out to make sure it's stored.
This is how far I've got:
int main(){
FILE * fp = fopen("sometext.txt", "r");
char text[100][100];
if(fp == NULL){
printf("File not found!");
}
else{
char aLine[20];
int row = 0;
while(fgets(aLine, 20, fp) != NULL){
printf("%s", aLine);
//strcpy(text[row], aLine); Trying to append a line (as row)
return 0;
}
Please don't start with "invest in some more time and look somewhere else because it's easy and has been answered". I'm bad at this, and I'm trying.
You can try this. Basically you need an array of arrays to store each line. You find the length of the longest line in the file and you allocate space for it. Then rewind the pointer to the start of the file and use fgets to get each line from the file and strdup to allocate space and copy the line to the respective position. Hope this helps.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]) {
FILE * fp = fopen("sometext.txt", "r");
int maxLineSize = 0, count = 0;
char c;
while ((c = fgetc(fp)) != EOF) {
if (c == '\n' && count > maxLineSize) maxLineSize = count;
if (c == '\n') count = 0;
count++;
}
rewind(fp);
char ** lines = NULL;
char * line = calloc(maxLineSize, sizeof(char));
for (int i = 0 ; fgets(line, maxLineSize + 1, fp) != NULL ; i++) { // +1 for \0
lines = realloc(lines, (i + 1) * sizeof(char *));
line[strcspn(line, "\n")] = 0; // optional if you want to cut \n from the end of the line
lines[i] = strdup(line);
printf("%s\n", lines[i]);
memset(line, maxLineSize, '\0');
}
fclose(fp);
}
You could solve it without copy
The follow code could work:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <math.h>
int main()
{
FILE * fp = fopen("sometext.txt", "r");
if(fp == NULL){
printf("File not found!");
return -1;
}
char text[100][20];
int row = 0;
while(row < 100 && fgets(text[row], sizeof(text[0]), fp) != NULL)
++row;
for (int i= 0; i != row; ++i)
fputs(text[i], stdout);
return 0;
}