473,328 Members | 1,343 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,328 software developers and data experts.

reading and writing incorrectly

Here is my code and output.
Why is it writing to the array incorrectly, when I rewinded the file to
the beginning?

CODE:

void ReadString (char *filename, int *lengthPtr)
{
FILE *ifp;
char txtFile[*lengthPtr];
char c;
int count = 0;
int items = 0;
int *dma;

/* opens the file*/
ifp = fopen (filename, "r");

if(ifp == NULL)
{
fprintf (stderr, "Error opening file\n");
exit (-1);
}

while (fscanf (ifp, "%c", &c)!= EOF)
{
items++;
}

*lengthPtr = items;

dma = malloc(items * sizeof(char));

if (dma == NULL)
{
printf("Not enough memory\n");
exit(-1);
}

rewind (ifp);

while (fscanf (ifp, "%c", &c)!= EOF)
{
txtFile[count] = c;
count++;
}

txtFile[count] = '\0';

count = 0;

while (txtFile != NULL)
{
printf ("%c", txtFile[count]);
count++;
}
printf ("\n\n");

fclose (ifp);
}

OUTPUT:
Enter the name of the file to analyze: pamphlet1.txt

���istoria sagrada d�����pL��"h�
L ���߅��,���OY�VYĂ����xX ��el
Occidente medieval. Dedicado a San Miguel en el ano
708 como consecuencia de apariciones milagrosas, fue confiado en el ano
966 por el Duque de Normandia a los monjes benedictinos que hicieron de
la
isla uno de los lugares mas importantes de peregrinaje del mundo
cristiano,
desarrollando la leyenda del obispo fundador Aubert. Los monjes
pusieron
en marcha un programa de construccion sobrehumano: los trabajos
prosiguieron
sin descanso desde el ano mil hasta principios del siglo XVI.

El visitante descubre asi un panorama de la arquitectura medieval,
recorriendo esta multitud de edificios, apinados en la punta del
penasco. El Mont Saint-Michel fue tambien una plaza fuerte
inexpugnable:
su heroica resistencia a los ingleses durante la guerra de los Cien
Anos
le sirvio para convertirse en un lugar simbolico de la identidad
nacional.
Las murallas que rodean el pueblo y las fortificaciones de la abadia
dan
testimonio de este papel preponderante. Despues de la transformacion de
la abadia en prision, a partir de la Revolucion hasta 1863, el
monasterio
convertido en monumento historico en 1874 fue objeto de grandes
restauraciones. Estas permiten a los visitantes volver a encontrar el
esplendor de un edificio que los hombres de la Edad Media veian como la
imagen de la Jerusalen Celestial en la tierra.

-----
Siga al guia

Tras haber atravesado la sala de los Guardias, entrada fortificada de
la
abadia, el visitante sube la escalera del Grand Degre que constituye el
acceso monumental a la iglesia abacial. Se avanza entre la iglesia, a
la
erecha, y las viviendas abaciales, a la izquierda, unidas por pasadizos
suspendidos. Estas viviendas, construidas desde finales del siglo XIV
hasta principios del siglo XVI, fueron la residencia senorial de los
abades.

La azotea del oeste esta constituida por el atrio primitivo de la
iglesia
abacial y por los primeros tramos de la nave destruidos en el siglo
XVIII
tras un incendio. La fachada neoclasica fue reconstruida en 1780. Desde
alli se puede apreciar una vista general de la bahia, desde la punta
del
Grouin hasta la punta de Champeaux: al oeste, el Mont-Dol; al norte el
islote de Tombelaine. La azotea ofrece, por otro lado, un excelente
punto
de mira sobre la aguja neogotica del campanario construida en 1897 y la
estatua del arcangel de cobre repujado y dorado con pan de oro. La
iglesia
abacial esta construida en la cima del penasco, sobre una plataforrna
constituida por cuatro criptas que rodean este y soportan los cuatro
brazos
de la cruz. La nave, caracteristica del arte romanico normando,
presenta
una elevacion a tres niveles: soportales, tribunas y ventanas altas. La
estructura de la nave esta guarnecida por una boveda de medio punto
artesonada como lo fueron la mayor parte de las iglesias romanicas de
Normandia. El coro romanico, derrumbado en 1421, se reedifico de 1446 a
1521 en estilo gotico flamigero.

La visita continua, al norte de la iglesia, por el monasterio gotico
denominado la Naravilla debido al caracter excepcional del edificio.
Fue construido tras el incendio de f 204 que asolo la abadia. El
claustro da al mar, al norte, y permite el acceso al refectorio, a
la cocina, a la iglesia, a los dormitorios, al archivo y a diferentes
escaleras que conducen a los niveles inferiores. Alrededor del jardin,
reconstituido en 1965, la arquitectura de las galerias del claustro,
donde la altura de las columnitas es la del cuerpo humano, creaba un
marco intimo para ia meditacion de los monjes.

El decorado de piedras angulares, esculpido en piedra de Caen, que
permite una escultura mas elaborada que el granito del conjunto del
edificio, estaba pintado originariamente. Actualmente solo se
distinguen
ya elementos vegetales esencialmente.

En el amplio refectorio, los monjes comian en silencio, mientras que el
lector, desde el pulpito de la pared sur, hacia la lectura. Las paredes
laterales de esta sala estan abiertas por estrechas ventanas invisibles
desde la entrada pero que dejan pasar un raudal de luz.

Por una escalera se accede al piso inferior donde se encuentran la sala
de trabajo de los monjes que mas tarde se denomino de los Caballeros,
asi
como la sala de los Huespedes, donde se recibia a los huespedes
insignes.
En la planta baja, se alimentaba y se albergaba a los peregrinos pobres
en la capellania, amplia sala dividida en dos naves por una hilera de
columnas. La bodega cercana, inmenso almacen donde reina una fresca
penumbra, se divide en compartimentos por dos filas de pilares
cuadrados:
el almacenamiento de las provisiones se organizaba asi de forma
racional.
En la bodega puede apreciarse una gran maqueta que data del ano 1701,
copia de un original realizado hacia 1690 conservado en el museo de
Planos- Relieves de Paris. Permite descubrir el Mont Saint-Michel de
antes
de la Revolucion. Igualmente se podra admirar en ella la maqueta a
tamano
natural del San Miguel de Fremiet que corona la aguja de la iglesia.
Se sale por los jardines del norte que extienden su sendero apacible,
frente a la inmensidad de la bahia, bajo las murallas abruptas de la
Maravilla.

Piedra angular- Parte de superficie aproximadamente triangular
comprendida entre la alzada de dos arcos.

Los tres niveles del monasterio reflejan, de arriba a abajo, la
organizarion de la sociedad medieval- el clero, la nobleza y el tercer
estado- y la jerarquia del alimento- espiritual, intelectual y
material.

Arco de medio punto- Se denomina asi a un arco o una boveda en
semicirculo.

Aparejo- Disposicion de los elementos de mamposteria.

Arco mitral- Se trata de un arco formado por dos curvas que forman
un angulo agudo en la parte superior.

Flamigero- Ultimo periodo gotico (en Francia a partir de finales del
siglo XIV) con predominio de decorados de curvas y contracurvas con
elementos en forma de llamas.

-----
Arquitectura- Arquitectura medieval

La abadia del Mont Saint-Michel ofrece un panorama completo de la
arquitectura medieval. La arquitectura prerromanica esta representada
por
la iglesia Notre- Dame- sous- Terre del siglo X, donde subsiste la
tradicion romana: muros muy gruesos construidos de pequenas piedras
sillares, arcos de medio punto+ aparejados en ladrillos planos. El
siglo
XI ofrece la plenitud de sus volumenes romanicos en las criptas del
Crucero y el lado sur de la nave de la iglesia. Los ornamentos de
mamposteria presentan un aparejo de piedras cuidado, de cimientos
regulares, de juntas finas.

El siglo XII busca estructuras constructivas mas ligeras y utiliza el
arco mitral en el lateral norte de la nave. En el Promenoir
(deambulatorio)
los arquitectos piensan en montar las bovedas sobre una estructura
de arcos diagonales. Esta innovacion conducira al nacimiento del arte
gotico. Este nuevo procedimiento permitira substituir los abovedados
romanicos macizos y gruesos por una estructura de ligeras semibovedas
soportadas por los arcos. De este modo, al quedar el peso repartido
sobre
los pilares, las paredes podran perforarse despues con aberturas cada
vez
mas grandes. El primer piso de la Maravilla, del siglo XIII, da
testimonio
de la tecnica de este sistema de construccion.

El coro flamigero del siglo XV expresa el resultado de la arquitectura
gotica.
La boveda que reposa sobre pilares ligeros, apuntalados en el exterior
por
majestuosos arbotantes, permitio transformar el santuario en un espacio
impregnado de luz.

-----
San Miguel

San Miguel de las cumbres

El monte, dedicado a San Miguel en el ano 708, fue junto con el Monte
Gargan
en Italia del Sur, uno de los primeros lugares de culto del arcangel en
Occidente. La devocion a san Miguel tiene una importancia muy
particular
en la sensibilidad religiosa medieval. El arcangel San Miguel tiene
tres
misiones: Juzga a las almas para separar a los elegidos de los
condenados,
les conduce al cielo protegiendoles de los demonios al acecho y,
finalmente,
guarda las puertas del Paraiso. Por ello, con frecuencia se le han
dedicado
cumbres cerca del cielo como Saint-Michel-de-l'Aiguilhe en el Puy,
Saint-Michel-de-Cuxa en los Pirineos, y se le han dedicado las capillas
altas en la parte superior de las entradas de algunas grandes iglesias
como
Tournus, Vezelay o Saint-Benoit-sur-Loire.

En el siglo XV, el culto del arcangel adquiere una nueva importancia
con
la creacion de la orden de San Miguel. El siglo XIX vuelve a descubrir
la
Edad Media: De ello da testimonio la estatua de Fremiet, elevada en el
vertice de la aguja en 1897.
a.outMANPATH=/usr/k5/man:/usr/local/man:/usr/share/man:/usr/X11R6/manSSH_AGENT_PID=4407SUPPORTED=en_US.UTF-8:en_US:enHOSTNAME=ecs021pc27.ucslab.umbc.eduDM_CO NTROL=/var/run/xdmctlHOST=ecs021pc27.ucslab.umbc.eduSHELL=/bin/tcshTERM=xtermXDM_MANAGED=/var/run/xdmctl/xdmctl-:0,maysd,mayfn,sched,method=classicQTDIR=/usr/lib/qt-3.3GROUP=rpcUSER=hale1LS_COLORS=no=00:fi=00:di=00; 34:ln=00;36:pi=40;33:so=00;35:bd=40;33;01:cd=40;33 ;01:or=01;05;37;41:mi=01;05;37;41:ex=00;32:*.cmd=0 0;32:*.exe=00;32:*.com=00;32:*.btm=00;32:*.bat=00; 32:*.sh=00;32:*.csh=00;32:*.tar=00;31:*.tgz=00;31: *.arj=00;31:*.taz=00;31:*.lzh=00;31:*.zip=00;31:*. z=00;31:*.Z=00;31:*.gz=00;31:*.bz2=00;31:*.bz=00;3 1:*.tz=00;31:*.rpm=00;31:*.cpio=00;31:*.jpg=00;35: *.gif=00;35:*.bmp=00;35:*.xbm=00;35:*.xpm=00;35:*. png=00;35:*.tif=00;35:SSH_AUTH_SOCK=/tmp/ssh-WUGuAQ4406/agent.4406HOSTTYPE=i386-linuxPATH=/afs/umbc.edu/users/h/a/hale1/home/bin:/usr/local/bin:/usr/bsd:/usr/bin:/bin:/usr/sbin:/sbin:/usr/bin/X11:/usr/local/X11:/etc:/usr/etc:.:/usr/k5/bin:/usr/afsws/bin:/bin:/usr/java/bin:/usr/afsws/bin:/usr/X11R6/binMAIL=/var/spool/mail/hale1DESKTOP_SESSION=defaultINPUTRC=/etc/inputrcPWD=/afs/umbc.edu/users/h/a/hale1/home/201/proj3LANG=en_US.UTF-8TZ=EST5EDTSSH_ASKPASS=/usr/libexec/openssh/gnome-ssh-askpassHOME=/afs/umbc.edu/users/h/a/hale1/homeSHLVL=2OSTYPE=linuxVENDOR=intelMACHTYPE=i386LO GNAME=hale1DBUS_SESSION_BUS_ADDRESS=unix:abstract=/tmp/dbus-Kb6Hp9HTiqLESSOPEN=|/usr/bin/lesspipe.sh
%sDISPLAY=:0.0G_BROKEN_FILENAMES=1GTK_RC_FILES=/etc/gtk/gtkrc:/afs/umbc.edu/users/h/a/hale1/home/.gtkrc-1.2-gnome2SESSION_MANAGER=local/ecs021pc27.ucslab.umbc.edu:/tmp/.ICE-unix/4406GNOME_KEYRING_SOCKET=/tmp/keyring-J9IJfa/socketGNOME_DESKTOP_SESSION_ID=DefaultCOLORTERM=gn ome-terminalWINDOWID=37748815EDITOR=/usr/local/bin/emacsa.outSegmentation
fault
The very beginning is incorrect and the middle is correct, and the end
is way off.

Nov 6 '06 #1
2 2359


On Nov 6, 7:50 am, "totoro2...@gmail.com" <totoro2...@gmail.com>
wrote:
Here is my code and output.
Why is it writing to the array incorrectly, when I rewinded the file to
the beginning?
This is an example for wrong addressing.
In the details you provided, you did not tell about what are the
contents of source file size and what is the size to read that you are
passing. And your program is not designed to check these two parameters
for all cases.

You have allocated memory to "dma" and then reading file contents to
txtFile[] which is decided by the length of file parameter? Analyse it
for a typical case when file size is 100KB and you pass 100 for
reading. Your system will behave abnormally.
>
The very beginning is incorrect and the middle is correct, and the end
is way off.
Nov 6 '06 #2
to********@gmail.com <to********@gmail.comwrote:
Here is my code and output.
Why is it writing to the array incorrectly, when I rewinded the file to
the beginning?
It got nothing to do with the rewind(), the problem is that you
are messing around with memory your program doesn't own.
CODE:
void ReadString (char *filename, int *lengthPtr)
{
FILE *ifp;
char txtFile[*lengthPtr];
Please note that this isn't allowed with a strictly C89 compliant
compiler, for that you can only define arrays with a length that's
known at compiler time.

And how do you now how long your file is going to be, wich would be
the only reasonable value what lengthPtr is pointing to could have?
char c;
int count = 0;
int items = 0;
int *dma;
/* opens the file*/
ifp = fopen (filename, "r");
if(ifp == NULL)
{
fprintf (stderr, "Error opening file\n");
exit (-1);
}
while (fscanf (ifp, "%c", &c)!= EOF)
{
items++;
}
*lengthPtr = items;
I get a suspision that you (wrongly) assume that this would magically
change the length of the txtFile char array, but which it doesn't! If
what lengthPrt is pointing to is 20, but you found that the actual
length of the file is 781, the txtFile array is still only 20 chars
long and using it for more than that will get you in bad trouble.
dma = malloc(items * sizeof(char));
Why did you define dma to be an int pointer when you want to store
a char pointer in it? Moreover, dma is never used in the rest of the
program, so what is this memory allocation supposed to be good for?
And you never deallocate the memory, so, once you have left this
function you're still holding on to some memory, but which you can't
use, not even free().
if (dma == NULL)
{
printf("Not enough memory\n");
exit(-1);
}
rewind (ifp);
while (fscanf (ifp, "%c", &c)!= EOF)
{
txtFile[count] = c;
count++;
}
If the number of chars you can read from the file is larger than
what lengthPtr pointed to *when the function was called* then you
write past the end of the txtFile array and all bets are off.
txtFile[count] = '\0';
If lengthPtr was pointing to a number with the exact number of
chars you can read from the file than this here would be another
problem since that's one additional character you need to store
but for which you wouldn't have enough room.
count = 0;
while (txtFile != NULL)
txtFile can never be NULL, it's an array and not a pointer. So it's
going to write and write and write until txtFile + count points to
memory you are not allowed to access and you get a segmentation fault.
Perhaps you meant

if (txtFile[count] != '\0')
{
printf ("%c", txtFile[count]);
count++;
}
printf ("\n\n");
fclose (ifp);
}
Ok, here's a version where I tried to get rid of the worst
problems. Unfortunately, I don't have much time at the moment
for testing (got to go to the dentist;-(), but I hope it
gives you an idea how in principle it could be done. And,
of course, there are many better ways to implement such a
function;-)

void ReadString (char *filename)
{
FILE *ifp;
char *txtFile;
char c;
int count = 0;
int items = 0;

/* opens the file*/
ifp = fopen (filename, "r");

if(ifp == NULL)
{
fprintf (stderr, "Error opening file\n");
exit (-1);
}

while (fscanf (ifp, "%c", &c)!= EOF)
{
items++;
}

txtFile = malloc((items + 1) * sizeof *txtFile);
if (txtFile == NULL)
{
printf("Not enough memory\n");
exit(-1);
}

rewind (ifp);

while (fscanf (ifp, "%c", &c)!= EOF)
{
txtFile[count++] = c;
}

txtFile[count] = '\0';

count = 0;

while (txtFile[count] != '\0')
{
printf ("%c", txtFile[count++]);
}
printf ("\n\n");

free(txtFile);

fclose (ifp);
}
Regards, Jens
--
\ Jens Thoms Toerring ___ jt@toerring.de
\__________________________ http://toerring.de
Nov 6 '06 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: fabrice | last post by:
Hello, I've got trouble reading a text file (event viewer dump) by using the getline() function... After 200 - 300 lines that are read correctly, it suddenly stops reading the rest of the...
4
by: Oliver Knoll | last post by:
According to my ANSI book, tmpfile() creates a file with wb+ mode (that is just writing, right?). How would one reopen it for reading? I got the following (which works): FILE *tmpFile =...
3
by: Matta | last post by:
Hi, I'm writing an NNTP based program that downloads articles from Usenet. I've run into a weird problem. It seems as if there is a bug somewhere that causes certain articles to download...
21
by: JoKur | last post by:
Hello, First let me tell you that I'm very new to C# and learning as I go. I'm trying to write a client application to communicate with a server (that I didn't write). Each message from the...
6
by: Bry | last post by:
I'm having problems writing (and reading) boolean data to the registry. // Write a boolean value to the registry // I've not included the obvious bits of code in these samples bool myBool =...
8
by: Jean-Marie Vaneskahian | last post by:
Reading - Parsing Records From An LDAP LDIF File In .Net? I am in need of a .Net class that will allow for the parsing of a LDAP LDIF file. An LDIF file is the standard format for representing...
6
by: arne.muller | last post by:
Hello, I've come across some problems reading strucutres from binary files. Basically I've some strutures typedef struct { int i; double x; int n; double *mz;
111
by: Tonio Cartonio | last post by:
I have to read characters from stdin and save them in a string. The problem is that I don't know how much characters will be read. Francesco -- ------------------------------------- ...
0
by: jenniamia | last post by:
I'm new to programming, so this might be simpler than I realize but I'd appreciate a push in the right direction. I'm using VS.NET 2005 with a database, SQL 2000. I'm writing in C# code and I'm...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.